mongoose save or update
// This will create another document if it doesn't exist
findByIdAndUpdate(_id, { something: 'updated' }, { upsert: true });
mongoose save or update
// This will create another document if it doesn't exist
findByIdAndUpdate(_id, { something: 'updated' }, { upsert: true });
mongoose update subdocument by id
//this method for add data to subdocument
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);
});
});
// alternative second method you can use this
BlogPost.findOneAndUpdate({_id: req.params.postId}, {$push:{ subDoc: req.body }}, (err, doc) => {
// do something here
});
update query in mongoose
var conditions = { name: 'bourne' }
, update = { $inc: { visits: 1 }}
Model.update(conditions, update, { multi: true }).then(updatedRows=>{
}).catch(err=>{
console.log(err)
})
updating an array of object in mongoose
Person.update(
{
_id: 5,
grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
},
{ $set: { "grades.$.std" : 6 } }
)
mongoose update array in object
Person.findOneAndUpdate({_id: id},
{
"$set": {[`items.$[outer].${propertyName}`]: value}
},
{
"arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
...
})
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us