【问题标题】:mongoose. updating embedded document in array猫鼬。更新数组中的嵌入文档
【发布时间】:2012-02-15 20:59:09
【问题描述】:

a official mongoose site 中,我发现了如何通过数组中的 _id 删除嵌入的文档:

post.comments.id(my_id).remove();
post.save(function (err) {
   // embedded comment with id `my_id` removed!
});

我有兴趣如何更新而不是删除这个?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    应该是这样的:

        YOURSCHEMA.update(
            { _id: "DocumentObjectid" , "ArrayName.id":"ArrayElementId" },
            { $set:{ "ArrayName.$.TheParameter":"newValue" } },
            { upsert: true }, 
            function(err){
    
            }
        );
    

    在此示例中,我正在搜索带有 id 参数的元素,但它可能是 objectId 类型的实际 _id 参数。

    另请参阅:MongooseJS Doc - Updating SetSimilar SO question

    【讨论】:

      【解决方案2】:

      你可以的

      var comment = post.comments.id(my_id);
      comment.author = 'Bruce Wayne';
      
      post.save(function (err) {
          // emmbeded comment with author updated     
      });
      

      【讨论】:

      • 当我更新嵌入式文档时,Save 似乎没有触发 - 并且将其标记为已更改也不会使其无效。
      【解决方案3】:

      更新到有关在 Mongoose 中处理子文档的最新文档。 http://mongoosejs.com/docs/subdocs.html

      var Parent = mongoose.model('Parent');
      var parent = new Parent;
      
      // create a comment
      parent.children.push({ name: 'Liesl' });
      var subdoc = parent.children[0];
      console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
      subdoc.isNew; // true
      
      parent.save(function (err) {
        if (err) return handleError(err)
        console.log('Success!');
      });
      

      【讨论】:

      • 这似乎不会更新嵌入的文档。
      猜你喜欢
      • 2015-04-21
      • 2012-04-29
      • 1970-01-01
      • 2011-10-25
      • 2012-05-11
      • 2013-02-02
      • 2015-08-14
      • 1970-01-01
      • 2019-09-30
      相关资源
      最近更新 更多