Node.js MongoDB Upsert 更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13808389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js MongoDB Upsert update
提问by mradfo21
I'm writing a little application which scores keywords. So if "beirut" and "education" get entered in, if they haven't been seen before, I want to create a mongo entry, and give them a score of 1. If they have, I want to increment their score by one. I'm trying to do this with one update command, but I think I might be doing it wrong.
我正在编写一个对关键字进行评分的小应用程序。所以如果输入了“beirut”和“education”,如果他们以前没有见过,我想创建一个mongo条目,给他们1分。如果他们有,我想把他们的分数加一. 我试图用一个更新命令来做到这一点,但我想我可能做错了。
- Ranking is the object representing the database
- "key" is the keyword
- ranking是代表数据库的对象
- “key”是关键字
rankingdb.update(
{keyword:key},
{keyword:key, {$inc:{score:1}}},
{upsert:true, safe:false},
function(err, data) {
if (err) {
console.log(err);
}
else {
console.log("score succeeded");
}
}
);
SyntaxError: Unexpected token {
SyntaxError: Unexpected token {
Can you not create a brand new document with an increment?
你不能用增量创建一个全新的文档吗?
回答by JohnnyHK
Your general approach is right, but as the error message suggests, you've got a syntax problem in your code.
您的一般方法是正确的,但正如错误消息所暗示的那样,您的代码中存在语法问题。
Try this instead:
试试这个:
rankingdb.update(
{keyword: key},
{$inc: {score: 1}},
{upsert: true, safe: false},
function(err,data){
if (err){
console.log(err);
}else{
console.log("score succeded");
}
}
);
When an upsert needs to create a new object it combines the fields from the selector (first parameter) and the update object (second parameter) when creating the object so you don't need to include the keywordfield in both.
当 upsert 需要创建一个新对象时,它会在创建对象时组合来自选择器(第一个参数)和更新对象(第二个参数)的keyword字段,因此您不需要在两者中都包含该字段。
Note that update()is deprecated in the 2.0 driver, so you should now use either updateOne()or updateMany().
请注意,update()在 2.0 驱动程序中已弃用,因此您现在应该使用updateOne()或updateMany()。

