如何知道Mongoose的upsert是否创建了一个新文档? [英] How to know if Mongoose's upsert created a new document?

查看:95
本文介绍了如何知道Mongoose的upsert是否创建了一个新文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node.js / express.js中有这个代码:

I have this code in node.js/express.js:

var User = mongoose.model('User');
var usersRouter = express.Router();
usersRouter.put('/:id', function(req, res) {
    req.body._id = req.params.id;
    var usr = new User(req.body);

    usr.validate(function (err) {
        if (err) {
            res.status(400).json({});
            return;
        }

        var upsertData = usr.toObject();
        delete upsertData._id;

        User.update({_id: usr._id}, upsertData, {upsert: true}, function(err) {
            if (err) {
                res.status(500).json({});
                return;
            }

            res.status(204).json({});
        });
    });
});

它工作正常,但如果有新文件,我想向客户发送不同的回复已创建(状态201,json在响应正文中)或现有的已更新(状态204)。

It works fine, but I would like to send a different response to the client if a new document has been created (status 201 with json in response body) or an existing one has been updated (status 204).

有没有办法告诉与回调的区别 User.update

Is there a way to tell the difference from the callback of User.update?

推荐答案

使用回调函数中的第三个参数:

Use the third parameter from callback function:

...
User.update({_id: usr._id}, upsertData, {upsert: true}, function(err, num, n) {
  if (err) {
     res.status(500).json({});
     return;
   }

   if (!n.updatedExisting) { 
       /* new document */
   }

   res.status(204).json({});
});
...

n 是这样的对象:

{ updatedExisting: false,
  upserted: <ObjectId>,
  n: 1,
  connectionId: 11,
  err: null,
  ok: 1 }

updatedExisting 属性 true 文档更新时 - 所以它是在之前创建的。如果它是 false ,则表示在此次调用期间创建了新文档。

updatedExisting property is true when a document was updated -- so it was created before. If it's false, then it means that the new document was created during this call.

这篇关于如何知道Mongoose的upsert是否创建了一个新文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆