Mongoose.js: how to implement create or update?

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);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)