mongoose updateOne code 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 findoneandupdate
const doc = await CharacterModel.findOneAndUpdate(
{ name: 'Jon Snow' },
{ title: 'King in the North' },
{ new: true }
);
doc.title;
Example 3: mongoose save or update
findByIdAndUpdate(_id, { something: 'updated' }, { upsert: true });
Example 4: mongoose model
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
Example 5: mongoose updateone example
await CharacterModel.updateOne({ name: 'Jon Snow' }, {
title: 'King in the North'
});
const doc = await CharacterModel.findOne();
doc.title;
Example 6: findone and update mongoose
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));
const doc = await Model.findOne({ name: 'Neo' });
console.log(doc.name);