我在貓鼬中使用批量操作以并發方式更新多個檔案。
更新資料如下:
let docUpdates = [
{
id : docId1,
status : "created",
$push : {
updates : {
status: "created",
referenceId : referenceId,
createdTimestamp : "2022-06-14T00:00:00.000Z"
}
}
},
{
id : docId2,
status : "completed",
$push : {
updates : {
status: "compelted",
referenceId : referenceId,
createdTimestamp : "2022-06-14T00:00:00.000Z"
}
}
},
];
// Update documents using bulk operation
let bulkUpdate = Model.collection.initializeOrderedBulkOp();
for (let i = 0; i < docUpdates.length; i ) {
bulkUpdate.find({_id : docUpdates[i].docId}).updateOne({ $set : docUpdates[i]})
}
當我執行上面的代碼片段時,我收到以下錯誤。
(node:468) UnhandledPromiseRejectionWarning: MongoBulkWriteError: The dollar ($) prefixed field '$push' in '$push' is not allowed in the context of an update's replacement document. Consider using an aggregation pipeline with $replaceWith.
at OrderedBulkOperation.handleWriteError (/usr/src/app/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js:884:22)
您能否幫助找到解決此錯誤的方法。
謝謝你,
KK
uj5u.com熱心網友回復:
問題不在于$push不受支持,而在于您在更新檔案中傳遞引數的方式,它被解釋為頂級欄位。請參閱有關欄位名稱注意事項的檔案,特別是有關檔案修改更新的部分。
這部分代碼updateOne({ $set : docUpdates[i]})等效于以下內容:
updateOne({
$set: {
id: docId1,
status: "created",
$push: {
updates: {
status: "created",
referenceId: referenceId,
createdTimestamp: "2022-06-14T00:00:00.000Z"
}
}
}
})
因為$push包含在 中$set,所以您告訴 MongoDB 將名為的欄位的值設定為具有名為 的欄位$push的檔案,該欄位updates具有status、referenceId和createdTimestamp欄位。
相反,您想要做的是指定具有兩個不同更新運算子的更新檔案。換句話說,$push需要與$set.
就像是:
updateOne({
$set: {
id: docId1,
status: "created"
},
$push: {
updates: {
status: "created",
referenceId: referenceId,
createdTimestamp: "2022-06-14T00:00:00.000Z"
}
}
})
如何在docUpdates陣列中表示它取決于您。也許您可以執行以下操作:
let docUpdates = [
{
id : docId1,
update : {
$set : {
status : "created"
},
$push : {
updates : {
status: "created",
referenceId : referenceId,
createdTimestamp : "2022-06-14T00:00:00.000Z"
}
}
}
}
// ... Other updates
]
并在回圈中使用它,如:
bulkUpdate.find({_id : docUpdates[i].docId}).updateOne(docUpdates[i].update)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491361.html
