【发布时间】:2021-06-27 23:25:54
【问题描述】:
我需要在一次更新调用中同时使用 $set 和 $push。我已经按照$push and $set in same MongoDB update中提到的那样做了
现在我的代码是
await this.collection.updateOne(
{ id },
[
{
$set: {
...changes,
"metadata.updated": new Date(),
"metadata.updatedBy": { id: updatedBy }
}
},
{
$push: {
history: {
user: { id: updatedBy },
type: HistoryType.TIME_ENTRY_UPDATED,
date: new Date(),
args: changes
}
}
}
]
);
但它正在抛出MongoError: Unrecognized pipeline stage name: '$push'
我的代码有什么问题。
我的 mongodb 服务器版本 - 4.2.9 节点包客户端版本 - ^2.2.36
【问题讨论】:
-
你已经使用了聚合管道的更新,所以你不能使用$push,因为它不是一个管道阶段,对于解决方案你可以使用$set,并且可以使用
$concatArrays和现有字段您要推送的历史记录和新对象。你可以在你当前的 $set 操作中使用$set: { ...// your existing changes, history: { $concatArrays: ["$history", [{user: { id: updatedBy }, type: HistoryType.TIME_ENTRY_UPDATED, date: new Date(), args: changes}]]