How to update embedded document in mongoose?

前端 未结 3 1468
自闭症患者
自闭症患者 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 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);
        });
      });
    };
    

提交回复
热议问题