Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.js: how to implement create or update?

Tags:

mongoose

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.

like image 830
WHITECOLOR Avatar asked Nov 12 '12 02:11

WHITECOLOR


People also ask

Does Mongoose automatically create collection?

Mongoose by default produces a collection name by passing the model name to the utils.

What is difference between save and create in Mongoose?

create() is a shortcut for saving one or more documents to the database. MyModel. create(docs) does new MyModel(doc). save() for every doc in docs.

How do I use Find ID and update?

As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.


1 Answers

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); 
like image 118
JohnnyHK Avatar answered Oct 07 '22 08:10

JohnnyHK