How to update embedded document in mongoose?

前端 未结 3 1467
自闭症患者
自闭症患者 2020-12-15 11:16

I\'ve looked through the mongoose API, and many questions on SO and on the google group, and still can\'t figure out updating embedded documents.

I\'m trying to upda

相关标签:
3条回答
  • 2020-12-15 11:46

    when you already have the user, you can just do something like this:

    var listing = req.user.userListings.id(req.params.listingId);
    
    listing.isRead = args.isRead;
    listing.isFavorite = args.isFavorite;
    listing.isArchived = args.isArchived;
    
    req.user.save(function (err) {
      // ...
    });
    

    as found here: http://mongoosejs.com/docs/subdocs.html

    Finding a sub-document

    Each document has an _id. DocumentArrays have a special id method for looking up a document by its _id.

    var doc = parent.children.id(id);
    

    * * warning * *

    as @zach pointed out, you have to declare the sub-document's schema before the actual document 's schema to be able to use the id() method.

    0 讨论(0)
  • 2020-12-15 12:00

    You have to save the parent object, and markModified the nested document.

    That´s the way we do it

    exports.update = function(req, res) {
      if(req.body._id) { delete req.body._id; }
      Profile.findById(req.params.id, function (err, profile) {
        if (err) { return handleError(res, err); }
        if(!profile) { return res.send(404); }
        var updated = _.merge(profile, req.body);
        updated.markModified('NestedObj');
        updated.save(function (err) {
          if (err) { return handleError(res, err); }
          return res.json(200, profile);
        });
      });
    };
    
    0 讨论(0)
  • 2020-12-15 12:06

    Is this just a mismatch on variables names?

    You have user.userListings[i].listingId in the for loop but user.userListings[i]._id in the find.

    Are you looking for listingId or _id?

    0 讨论(0)
提交回复
热议问题