使用 update() 获取受影响文档的 ID [英] Get ID of affected document by using update()
问题描述
我用它来做一个更新插入:
I'm using this for doing an upsert:
Articles.update(
{ title: title },
{
title: title,
parent: type
},
{ upsert: true },
function(res) {
return console.log(res);
}
);
console.log(needToGetID);
现在我需要获取已更新或插入的文档的 _id.我以为我可以通过回调得到它,但是 res
是未定义的.我假设只有一个由查询定义的唯一文档.
Now I need to get the _id of the document which has been updated or inserted. I thought I can get that via callback, but res
is undefined.
I assume there is just one unique document which is defined by the query.
更新
忘了说我用的是meteor...
Forgot to mention that I'm using meteor...
推荐答案
.update()
的意图基本上只是更新"匹配的文档(因为multi"也可以在这里应用)并完成它,因此特别是考虑到这个可以"应用于多个文档然后返回这样的信息不会真的就该操作而言是有意义的.
The intent of .update()
is to basically just "update" the matching document(s) ( as "multi" can also be applied here ) and be done with it, therefore that especially considering this "could" be applied to multiple documents then returning such information would not really make sense in the terms of that operation.
但是,如果您的意图是修改单个特定文档",则 .findOneAndUpdate()
方法将适用,假设您使用的是猫鼬:
However if your intent is to modifiy a single "specific docucment", then the .findOneAndUpdate()
method would apply assuming you are using mongoose:
Articles.findOneAndUpdate(
{ title: title },
{
title: title,
parent: type
},
{ upsert: true, new: true },
function(res) {
return console.log(res);
}
);
还要注意 new: true
很重要,因为没有它,默认行为是返回之前"它被语句修改的文档.
Also note the new: true
which is important, as without it the default behavior is to return the document "before" it was modified by the statement.
无论如何,因为这里返回的是匹配和修改的文档,所以 _id
和任何其他值都存在于响应中.
At any rate, as the return here is the document that is matched and modified, then the _id
and any other value is present in the response.
使用meteor,您可以添加插件来启用.findAndModify()
这是根方法:
With meteor you can add a plugin to enable .findAndModify()
which is the root method:
meteor add fongandrew:find-and-modify
然后在代码中:
Articles.findAndModify(
{
"query": { title: title },
"update": {
title: title,
parent: type
},
"upsert": true,
"new": true
},
function(res) {
return console.log(res);
}
);
请注意,您还应该真正使用 $set
操作符,因为没有它,更改基本上覆盖"了目标文档:
Note that you should also really be using the $set
operator, as without it the changes basically "overwrite" the target document:
Articles.findAndModify(
{
"query": { "title": title },
"update": {
"$set": {
"parent": type
}
},
"upsert": true,
"new": true
},
function(res) {
return console.log(res);
}
);
这篇关于使用 update() 获取受影响文档的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!