mongoose updateone example
Example 1: mongoose find and update prop
var query = {'username': req.user.username};
req.newData.username = req.user.username;
MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
if (err) return res.send(500, {error: err});
return res.send('Succesfully saved.');
});
Example 2: mongoose updatemany example
User.update({"created": false}, {"$set":{"created": true}}, {"multi": true}, (err, writeResult) => {});
Example 3: mongoose updateone example
// Update the document using `updateOne()`
await CharacterModel.updateOne({ name: 'Jon Snow' }, {
title: 'King in the North'
});
// Load the document to see the updated value
const doc = await CharacterModel.findOne();
doc.title; // "King in the North"
Example 4: findone and update mongoose
// Using queries with promise chaining
Model.findOne({ name: 'Mr. Anderson' }).
then(doc => Model.updateOne({ _id: doc._id }, { name: 'Neo' })).
then(() => Model.findOne({ name: 'Neo' })).
then(doc => console.log(doc.name)); // 'Neo'
// Using queries with async/await
const doc = await Model.findOne({ name: 'Neo' });
console.log(doc.name); // 'Neo'
Example 5: 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)
})
Example 6: updateone mongodb examples
const query = { "name": "football" };
const update = {
"$push": {
"reviews": {
"username": "tombradyfan",
"comment": "I love football!!!"
}
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully added a new review.`)
}
})
.catch(err => console.error(`Failed to add review: ${err}`))