Mongoose.js: how to implement create or update?

后端 未结 1 525
情歌与酒
情歌与酒 2020-12-04 21:28

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

1条回答
  •  悲哀的现实
    2020-12-04 21:34

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

    0 讨论(0)
提交回复
热议问题