[英]How to know if Mongoose's upsert created a new document?
I have this code in node.js/express.js: 我在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({});
});
});
});
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). 它工作正常,但我想在创建新文档时向客户端发送不同的响应(状态201,响应正文中为json)或现有的已更新(状态204)。
Is there a way to tell the difference from the callback of User.update
? 有没有办法区分
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
is an object like this: n
是这样的对象:
{ updatedExisting: false,
upserted: <ObjectId>,
n: 1,
connectionId: 11,
err: null,
ok: 1 }
updatedExisting
property is true
when a document was updated -- so it was created before. 更新文档时,
updatedExisting
属性为true
- 因此它是在之前创建的。 If it's false
, then it means that the new document was created during this call. 如果它为
false
,则表示在此调用期间创建了新文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.