2015-10-20 58 views
0

我要怎么写猫鼬功能,将查询这mongo查询基于给定的userId(我不能将此添加到查询,也需要)。猫鼬elemMatch和公司查询基于ID

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 
     } 
    ); 

回答

1

您需要使用findOneAndUpdate而不是findByIdAndUpdate,如果你想匹配而不仅仅是_id任何东西。此处也不需要使用$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) { ... } 
); 
+0

你是伟大的... –