【问题标题】:Update embedded mongoose document in array更新数组中嵌入的猫鼬文档
【发布时间】:2015-04-21 13:05:27
【问题描述】:

假设我在书籍收藏中有以下文档:

{
  _id:0 ,
  item: "TBD",
  stock: 0,
  info: { publisher: "1111", pages: 430 },
  tags: [ "technology", "computer" ],
  ratings: [ { _id:id1, by: "ijk", rating: 4 }, {_id:id2 by: "lmn", rating: 5 } ],
  reorder: false
}

我想更新ratings[k].rating 的值,我只知道集合的 id 和数组评级中存在的对象的 _id。

mongoDB的教程有下面的例子,它使用了对象在数组中的位置,但我想如果更新只能通过知道位置来完成,这意味着我必须先找到位置然后再继续与更新?我可以只用一个电话进行更新吗?如果可以,我该怎么做?

db.books.update(    
   { _id: 1 },
   {
     $inc: { stock: 5 },
     $set: {
       item: "ABC123",
       "info.publisher": "2222",
       tags: [ "software" ],
       "ratings.1": { by: "xyz", rating: 3 }
     }
   }
)

【问题讨论】:

  • 您的意思是您知道_idratings 中的另一个_id 的值吗?并且您想在评级中更新评级。对吗?
  • 这正是我的意思...我尝试了不同的方法,但没有一种方法真正更新了我想要的属性 rating 的值。

标签: arrays mongoose document


【解决方案1】:

抱歉回复晚了;我想这就是你想用mongoose 做的事情。

Books.findOneAndUpdate({
        _id: 1,
        'ratings._id': id1
    },
    {
        $set: {
            'ratings.$.rating' : 3
        }
    }, function(err, book){
        // Response
    });

【讨论】:

    【解决方案2】:

    Positional operator 可以帮到你:

    db.books.update(
       // find book by `book_id` with `rating_id` specified
       { "_id": book_id, "ratings._id": rating_id },
    
       // set new `value` for that rating
       { $set: { 'ratings.$.rating': value }} 
    );
    

    $ 将保存匹配文档的位置

    【讨论】:

    • 我收到以下错误(代码 16837):[MongoError: cannot use the part (ratings of rating._id) 遍历元素 ((ratings: [Obj1], [Obj2]))
    猜你喜欢
    • 2012-02-15
    • 2012-04-29
    • 1970-01-01
    • 2011-10-25
    • 2012-05-11
    • 2013-02-02
    • 2015-08-14
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多