There are a few posts about this (here and here, for example), but none of them use a native Mongoose method for this. (The first one uses $set
, the second one uses the extend
npm package. Seems like there should be a "native mongoose" way to do this though.
Schema:
var blogPostSchema = new mongoose.Schema({
title: String,
comments: [{
body: String
}]
});
Here's what I tried originally:
BlogPost.findById(req.params.postId, function (err, post) {
var subDoc = post.comments.id(req.params.commentId);
subDoc = req.body;
post.save(function (err) {
if (err) return res.status(500).send(err);
res.send(post);
});
});
Problem is this line: subDoc = req.body
isn't actually changing the parent doc's subDoc, but rather is just passed by reference. Nothing actually changes in the database after a save()
call.
The extend
package fixes this by merging the two objects together, as shown in the second SO post linked above (and again here). But isn't there a way to get around this using some Mongoose API method? I can't find anything in the documentation about it (only how to add new subdocs and remove subdocs).
An alternative I wrote was this:
for (var key in subDoc) {
subDoc[key] = req.body[key] || subDoc[key];
}
which also works, but I wasn't sure if there was anything dangerous about doing it this way. Maybe this is the best way?
Thanks in advance!