Mongoose.js: how to implement create or update?

Mongoose

Mongoose Problem Overview


I have a request which body contains data and _id

What is the better way to implement code that will update if record with _id exists and will create one is there is no one? My code:

var obj = req.body;
Model.findById(obj._id, function(err, data){
    if (!data){
        var model = new Model(obj)
        model.save(function(err, data){
            res.send({method: 'create', error: err, data: data})
        })
    } else {
        Model.findByIdAndUpdate(obj._id, obj, function(){
            res.send({method: 'update', error: err, data: data})
        })
    }

I'm just thinking maybe there is beter way of doing this.

Mongoose Solutions


Solution 1 - Mongoose

You can do that with a single upsert:

var obj = req.body;
var id = obj._id;
delete obj._id;
if (id) {
    Model.update({_id: id}, obj, {upsert: true}, function (err) {...});
}

The caveat is that your model's defaults and middleware (if any) will not be applied.

Mongoose 4.x Update

You can now use the setDefaultOnInsert option to also apply defaults if the upsert creates a new document.

Model.update({_id: id}, obj, {upsert: true, setDefaultsOnInsert: true}, cb);

Solution 2 - Mongoose

 var obj = req.body;
 var id = obj._id;
 delete obj._id;
 model.findOneAndUpdate({ _id: id }, obj, {
                     new: true,
                     upsert: true, // Make this update into an upsert
 });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWHITECOLORView Question on Stackoverflow
Solution 1 - MongooseJohnnyHKView Answer on Stackoverflow
Solution 2 - MongoosehayelomView Answer on Stackoverflow