How to update a object in mongodb via mongoose?
Now you can update directly .
OrganizationModel.update(
{name: 'Koka'},
{'address.street': 'new street name'},
callback);
I can't find any docs that cover this simple case so I can see why you're having trouble. But it's as simple as using a $set
with a key that uses dot notation to reference the embedded field:
OrganizationModel.update(
{name: 'Koka'},
{$set: {'address.street': 'new street name'}},
callback);
Using Document set also, specified properties can be updated. With this approach, we can use "save" which validates the data also.
doc.set({
path : value
, path2 : {
path : value
}
}
Example: Update Product schema using Document set and save.
// Update the product
let productToUpdate = await Product.findById(req.params.id);
if (!productToUpdate) {
throw new NotFoundError();
}
productToUpdate.set({title:"New Title"});
await productToUpdate.save();
Note - This can be used to update the multiple and nested properties also.