gpt4 book ai didi

node.js - Mongoose 更新插入数据

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:29 28 4
gpt4 key购买 nike

当我尝试运行 findOneAndUpdate 时遇到以下问题

    MongoError: E11000 duplicate key error collection: AdStitchr.listeners index: uuid dup key: { UUID: "4502191d-1975-463d-8fc1-8ab3537cc9c8" }
at Connection.<anonymous> (C:\Users\russe\node_modules\mongodb\lib\core\connection\pool.js:466:61) at Connection.emit (events.js:210:5)
at processMessage (C:\Users\russe\node_modules\mongodb\lib\core\connection\connection.js:384:10) at TLSSocket.<anonymous> (C:\Users\russe\node_modules\mongodb\lib\core\connection\connection.js:553:15) at TLSSocket.emit (events.js:210:5)
at addChunk (_stream_readable.js:326:12)
at readableAddChunk (_stream_readable.js:301:11)
at TLSSocket.Readable.push (_stream_readable.js:235:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:182:23) {
operationTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1580080312 },
ok: 0,
errmsg: 'E11000 duplicate key error collection: AdStitchr.listeners index: uuid dup key: { UUID: "4502191d-1975-463d-8fc1-8ab3537cc9c8" }',
code: 11000,
codeName: 'DuplicateKey',
keyPattern: { UUID: 1 },
keyValue: { UUID: '4502191d-1975-463d-8fc1-8ab3537cc9c8' },
'$clusterTime': {
clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1580080312 },
signature: { hash: [Binary], keyId: [Long] }
},
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
}

现在我明白错误是说它不能这样做,因为

duplicate key error collection: AdStitchr.listeners index: uuid dup key: { UUID: "4502191d-1975-463d-8fc1-8ab3537cc9c8"

但是,它不应该尝试创建新插入。脚本应该做的是更新该文档,因为它已经存在并包含更新中的数据。

 var query = userData,
update = {$set:{
"endtime":Date.now()
}},
options = { upsert: true, setDefaultsOnInsert: true};
Listeners.findOneAndUpdate(query, update, options, function(error, result) {
if (!error) {
// If the document doesn't exist
if (!result) {
// Create it
// result = new Listeners(userData);
}
// Save the document
/* result.save(function(error) {
if (!error) {
// Do something with the document
} else {
throw error;
}
});*/
}
else{
console.log(error);
}

查询

const userData = {"UUID": query.uuid, "ipaddress":ip, "station":query.station,"starttime":Date.now()};

var update = {'$set':{ “结束时间”:Date.now() }},

No Endtime is stored indexes

最佳答案

userdata 变量作为查询传递,这意味着应满足以下所有四个条件:

const userData = {"UUID": query.uuid, "ipaddress":ip, "station":query.station,"starttime":Date.now()};

问题是 "starttime":Date.now() 每次运行此代码时都会生成新值,这会导致没有匹配的数据库文档,因此由于您在数据库上运行 upsert,因此会出现插入尝试。尝试删除动态评估的条件:

const userData = {"UUID": query.uuid, "ipaddress":ip, "station":query.station };

关于node.js - Mongoose 更新插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923629/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com