Node.js mongodb update upsert创建新记录
我有这样的记录Node.js mongodb update upsert创建新记录,node.js,mongodb,Node.js,Mongodb,我有这样的记录 { "_id" : ObjectId("57025c35e31f7274c1195c26"), "token" : "0ffed58b-57ed-4a2a-bb09-97c64f0f2bd2", "key" : "silly key", "user" : ObjectId("55e3f8fcc78dc516096dc3e2"), "twlprofile" : "Test Blog" } 这是该系列中唯一的一款。 我正在尝试更新,如果找不到
{
"_id" : ObjectId("57025c35e31f7274c1195c26"),
"token" : "0ffed58b-57ed-4a2a-bb09-97c64f0f2bd2",
"key" : "silly key",
"user" : ObjectId("55e3f8fcc78dc516096dc3e2"),
"twlprofile" : "Test Blog"
}
这是该系列中唯一的一款。
我正在尝试更新
,如果找不到任何内容,则需要更新以更新插入,因此我有此代码
var id = "55e3f8fcc78dc516096dc3e2";
var tokendoc = {
"token": "05c50aa0-5a8c-4fad-b27f-db64a0355b4f",
"key": "silly key",
"user": "55e3f8fcc78dc516096dc3e2",
"twlprofile": "Test Blog"
}
var tokenrecord = tokensCollection.update(
{ where: { user: id } },
tokendoc,
{ upsert: true },
function(err,tokenres){
//this part not important right now
});
如果我运行它,它将插入另一个具有相同用户属性的文档。我还尝试将BSON.ObjectID与id变量一起使用,但没有任何帮助
我怎样才能让它像一个真正的专家一样工作 使用updateOne而不是update,那么它将工作
{where:{user:id}}
应该是{user:id}
。如果那里没有文档,updateOne或findOneAndUpdate都不能插入任何内容,即使使用upsert:true。将用户id查询从何处更改为仅用户:id工作。为什么呢?有些部分不起作用,除非我使用where,有些部分不起作用。阅读关于where的文档似乎并不能解释为什么会这样。