![](/img/trans.png)
[英]Get access to the "current element" when traversing a mongoDB (mongoose) array
[英]MongoDB: Access current value of document when adding element to array via $push
我有一個集合MyCollection
,它基本上由它的_id
和一個名為comment
的字符串組成。 該集合應該是可批量更新的。
這樣做是這樣的:
for (const obj of inputObjects) {
bulkObjectsToWrite.push({
updateOne: {
filter: { _id: obj._id },
update: {
$set: {
comment: obj.comment
}
}
}
})
}
await MyCollection.bulkWrite(bulkObjectsToWrite)
到目前為止,一切都很好。
但是,現在的要求是,應該添加一個commentHistory
,它應該看起來像[{"oldValue": "oldValueOfComment", "newValue": "newValueOfComment"}, ...]
我知道我需要使用$push
將新的 object 添加到commentHistory
數組。 但是我如何訪問當前更新的文檔的comment
,即它的當前值?
我試過了
$push: {
commentHistory: {
newValue: obj.comment,
oldValue: '$comment',
},
},
但無濟於事。 字符串$comment
被硬編碼添加,而不是被訪問的字段。
(使用 Mongoose 5.12.10 和 Mongo 4.4.18)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.