Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Or Update Mongoose

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

like image 912
Ollie Avatar asked May 31 '17 14:05

Ollie


People also ask

What does save () do in Mongoose?

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.

What is difference between save and update method in MongoDB?

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.

How do I update my Mongoose?

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?

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.


1 Answers

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

like image 62
CD-jS Avatar answered Oct 03 '22 23:10

CD-jS