In the a official mongoose site I've found how can I remove embedded document by _id in array:
post.comments.id(my_id).remove();
post.save(function (err) {
// embedded comment with id `my_id` removed!
});
I'm interested how can I update instead removing this one?
Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.
$in -The $in operator selects the documents where the value of a field equals any value in the specified array. 1) {multi:true} to update Multiple documents in mongoose . 2)use update query to update Multiple documents ,If you are using findOneAndUpdate query only one record will be updated.
The save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.
You can also overwrite Mongoose's default _id with your own _id . Just be careful: Mongoose will refuse to save a document that doesn't have an _id , so you're responsible for setting _id if you define your own _id path.
It shoud look something like this:
YOURSCHEMA.update(
{ _id: "DocumentObjectid" , "ArrayName.id":"ArrayElementId" },
{ $set:{ "ArrayName.$.TheParameter":"newValue" } },
{ upsert: true },
function(err){
}
);
In this exemple I'm searching an element with an id parameter, but it could be the actual _id parameter of type objectId.
Also see: MongooseJS Doc - Updating Set and Similar SO question
Update to latest docs on dealing with sub documents in Mongoose. http://mongoosejs.com/docs/subdocs.html
var Parent = mongoose.model('Parent');
var parent = new Parent;
// create a comment
parent.children.push({ name: 'Liesl' });
var subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
parent.save(function (err) {
if (err) return handleError(err)
console.log('Success!');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With