【问题标题】:Mongoose elemMatch and inc query based on id基于 id 的 Mongoose elemMatch 和 inc 查询
【发布时间】:2015-10-21 04:11:53
【问题描述】:

我将如何编写基于给定 userId 查询此 mongo 查询的 mongoose 函数(我无法将其添加到查询中,也需要它)。

db.users.update({ categories : { $elemMatch: { name: "Sport"  }  }  },
                {$inc: {"categories.$.points": 6666, points : 7777}})

这对我没有帮助。

User.findByIdAndUpdate(
        request.params.userId,
        //{ $inc: { points: 1 }},
        { categories : { $elemMatch: { name: "Spor" }}}, 
        {$inc: {"categories.$.points": 6666, points : 7777}},
        //{ safe: true, upsert: true, new : true },
        function(err, user) {
          if (!err) {
            return reply(user); // HTTP 201
          }
          if (11000 === err.code || 11001 === err.code) {
            return reply(Boom.forbidden("please provide another user id, it already exist!"));
          }
          return reply(Boom.forbidden(err)); // HTTP 403
        }
    );

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    如果您想匹配除_id 之外的任何内容,则需要使用findOneAndUpdate 而不是findByIdAndUpdate。您也不需要在此处使用 $elemMatch,因为您只匹配 categories 数组中的单个字段,因此可以使用简单的点表示法字段匹配。

    应该是这样的:

    User.findOneAndUpdate(
        { _id: request.params.userId, "categories.name": "Sport" }, 
        { $inc: { "categories.$.points": 6666, points : 7777 }},
        { safe: true, upsert: true, new: true },
        function(err, user) { ... }
    );
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 2013-12-21
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2020-08-14
      相关资源
      最近更新 更多