1

I have a shema with nested documents:



    var BlogSchema = new mongoose.Schema({
    ...    
        comments    : [Comments],
    ...
    });

and trying to update a comment



    router.post('/comments/:id', function (req, res, next) {    
        Blog.findOneAndUpdate( 
            { 'comments._id': req.params.id   },     
            { "$set": {"comments.$": req.body}},

            function (err, post) {
                if (err) {
                    return next(err);
                }
                res.json(post);
        });
    });

with request body


     {"text": "test comment 2"}

On the request launch it returns a blog post with unchanged comments. Launching GET request I receive updated blog post with the correct comment updated, but: it lost all fields, except text with new content. Even _id is removed.

Can I use findAndUpdate function with such "partial" input objects, modifying only fields mentioned there, but keeping others as is?

And how may I return already modified object from the function without additional find-like requests?

Mario Trucco
  • 1,933
  • 3
  • 33
  • 45
anton
  • 247
  • 3
  • 13

0 Answers0