mongoose. updating embedded document in array

前端 未结 3 652
鱼传尺愫
鱼传尺愫 2021-01-02 05:06

In the a official mongoose site I\'ve found how can I remove embedded document by _id in array:

post.comments.id(my_id).remove();
post.save(function (err) {
         


        
相关标签:
3条回答
  • 2021-01-02 05:34

    It shoud look something like this:

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

    In this exemple I'm searching an element with an id parameter, but it could be the actual _id parameter of type objectId.

    Also see: MongooseJS Doc - Updating Set and Similar SO question

    0 讨论(0)
  • 2021-01-02 05:45

    Update to latest docs on dealing with sub documents in 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!');
    });
    
    0 讨论(0)
  • 2021-01-02 05:47

    You could do

    var comment = post.comments.id(my_id);
    comment.author = 'Bruce Wayne';
    
    post.save(function (err) {
        // emmbeded comment with author updated     
    });
    
    0 讨论(0)
提交回复
热议问题