Is there a nice way of either saving, or updating a document in mongoose? Something like what I'm after below
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 the help all
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.
The save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.
What is difference between update and findOneAndUpdate? The findOneAndUpdate() method returns the document after the update, whereas the updateOne() method of MongoDB also updates one document but it does not return any document.
I think what you're looking for is called an 'upsert'.
You can do this by using findOneAndUpdate and passing the { upsert: true } option, something like the below example:
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're saving a new document or updating an existing one. If you want to return the modified document in the response data then you can also add the { new: true }
option.
Documentation here for findOneAndUpdate: http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With