【问题标题】:MongoError: Unrecognized pipeline stage name: '$pushMongoError:无法识别的管道阶段名称:'$push
【发布时间】: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}]]

标签: node.js mongodb


【解决方案1】:

我正在使用 mongodb 节点本机驱动程序,并且 我安装的mongodb版本是v4.4.5,我的node版本是v14.15.4

我也遇到了这个问题,我将更新正文命令更改为下面,它对我有用。

 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
                    }
                }
         }
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2021-02-10
    • 2019-09-01
    • 2020-10-07
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多