Save or update Mongoose
Is there a good way to save or update a document in mongoose? Something like what I'm after at the bottom
let campaign = new Campaign({
title: req.body.title,
market: req.body.market,
logo: req.body.logo,
additional_question_information: question,
status: status
});
campaign.saveOrUpdate().then(function() { ... }
Thanks for helping everyone
source to share
I think what you are looking for is called "upsert".
You can do this using findOneAndUpdate and passing in the {upsert: true} parameter, something like the example below:
let campaign = new Campaign({
title: req.body.title,
market: req.body.market,
logo: req.body.logo,
additional_question_information: question,
status: status
});
Campaign.findOneAndUpdate({
_id: mongoose.Types.ObjectId('CAMPAIGN ID TO SEARCH FOR')
}, campaign, { upsert: true }, function(err, res) {
// Deal with the response data/error
});
The first parameter to findOneAndUpdate is the query used to see if you are saving a new document or updating an existing one. If you want to revert the modified document in the response data, you can also add a parameter { new: true }
.
Documentation here for findOneAndUpdate: http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
source to share
You can use MongoDB findAndModify function. In mongoose this is supported by calling findOneAndUpdate (). Here is the documentation for it. http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate
Note that in the third argument, it expects the object to be passed with parameters. You want to use { upsert : true }
there to create a new document if it doesn't exist.
source to share