所以我有这个代码,可以在第一次尝试时保存,但是当用户访问另一个站点时,我需要它在历史数组下添加一个新的子数组。
注意:如果没有找到任何内容(意味着UUID
,我仍然需要它.save
)。
const userData = {"UUID": query.uuid, "ipaddress":ip, "history":[{"HID":hid,"station":req.params.stationname, starttime: starttimestamp}]};
var listener = new Listeners(userData);
listener.save(function (err, book) {
if (err) return console.error(err);
console.log(book.UUID + " saved to collection.");
});
正确的做法是什么?
我收到以下错误
{ MongoError: E11000 duplicate key error collection: AdStitchr.listeners index: UUID dup key: { UUID: "72296e08-2086-3b25-b66f-09fe14e7a1b9" }
at Connection.<anonymous> (/root/adstichrplayer/node_modules/mongodb/lib/core/connection/pool.js:466:61)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at processMessage (/root/adstichrplayer/node_modules/mongodb/lib/core/connection/connection.js:384:10)
at TLSSocket.<anonymous> (/root/adstichrplayer/node_modules/mongodb/lib/core/connection/connection.js:553:15)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at TLSSocket.Readable.push (_stream_readable.js:208:10)
at TLSWrap.onread (net.js:607:20)
operationTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1592964549 },
ok: 0,
errmsg: 'E11000 duplicate key error collection: AdStitchr.listeners index: UUID dup key: { UUID: "72296e08-2086-3b25-b66f-09fe14e7a1b9" }',
code: 11000,
codeName: 'DuplicateKey',
keyPattern: { UUID: 1 },
keyValue: { UUID: '72296e08-2086-3b25-b66f-09fe14e7a1b9' },
'$clusterTime':
{ clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1592964549 },
signature: { hash: [Object], keyId: [Object] } },
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {} }
当我使用时
const userData = {"UUID": query.uuid, "ipaddress":ip, "history":[{"HID":hid,"station":req.params.stationname, starttime: starttimestamp}]};
Listeners.findOneAndUpdate(
userData,
{ userData }, { upsert: true }, function(err) {
if (err) {
console.log('ERROR when submitting round');
console.log(err);
}
});
最佳答案
如果由于某种原因您只能访问变量userData
,并且考虑到它的有效对象值为:
const userData = {"UUID": query.uuid, "ipaddress":ip, "history":[{"HID":hid,"station":req.params.stationname, starttime: starttimestamp}]}
你可以这样做:
Listeners.findOneAndUpdate(
{"UUID": userData.UUID, "ipaddress":userData.ipaddress },
{ $push: { history: userData.history[0] } },
{ upsert: true }, function(err) {
if (err) {
console.log('ERROR when submitting round');
console.log(err);
}
});
关于node.js - 注意插入新的子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62546424/