Reputation: 1149
I have an embedded document that needs to be updated. I am having trouble figuring out how to update the document given the id. Here is what I have so far, but it doesn't work:
var Post = require('../models/post');
var comment_id = 5394f5be2f6953083908db47;
var updateData = {
comment: req.body.comment,
title: req.body.title
};
Post.update({ comments : { _id : comment_id } }, updateData, function(err,data) {
return res.json({success: true});
});
var postCommentSchema = mongoose.Schema({
title : String,
comment : String,
user : String,
tags : [],
created : {
type: Date,
default: Date.now
}
});
var postSchema = mongoose.Schema({
post : String,
title : String,
created : {
type: Date,
default: Date.now
},
comments : [postCommentSchema]
});
module.exports = mongoose.model('Posts', postSchema);
Upvotes: 0
Views: 330
Reputation: 151072
Your "comment_id" variable needs to be quoted to be valid JavaScript. But basically as this is a singular _id
value that cannot appear more than once you can use "dot notation" to address the required field. Then you need a positional $
operator to reference the index of the field that you matched in the update side.
Also you need the $set
operator otherwise your "updateData" object is going to overwrite the existing data in your array member you are referencing, namely the date which is missing here:
var comment_id = "5394f5be2f6953083908db47";
Post.update(
{ "comments._id" : comment_id } },
{ "$set": {
"comments.$.comment": req.body.comments,
"comments.$.title": req.body.title
} },
function(err,numAffected) {
return res.json({success: true});
}
);
Though you are not using it here, the second argument to the callback for .update()
is the number of documents affected by the statement and not the actual document or data. To get the document back as a result, look at methods such as .findOneAndUpdate()
in the mongoose API documentation.
Also the official MongoDB documentation for .update()
shows several common usage cases.
Upvotes: 1