【问题标题】:NodeJS Mongoose update documentNodeJS Mongoose 更新文档
【发布时间】:2020-07-09 17:51:52
【问题描述】:

我正在尝试在 MongoDB 集合中更新或创建文档,以这种方式使用“mongoose”:

        this.statsModel.findOne(
            {product_id: requestData.ean},
        ).then((stats: mongoose.Schema) => {
            const productId: string = requestData.ean;
            // Update stats with the new scan...
            const beforeStats: mongoose.Schema = stats;

            const scan: any = {
                coords: {
                    lat: requestData.lat,
                    lon: requestData.lon,
                },
                at: new Date(),
            };

            if (stats) {
                stats.scans.push(scan);
                stats.update();
            } else {
                const newStat = new this.statsModel();
                newStat._id = requestData.ean;
                newStat.product_id = requestData.ean;
                newStat.scans = [scan];
                newStat.purchases = [];
                newStat.save();
            }

当此代码运行时,如果有统计文档,则“扫描”属性中不会出现新元素。

如果未找到 stats 文档,则正确创建文档。

我尝试将“update()”方法更改为“save()”方法,但是,这样,我得到一个“版本错误没有匹配的文档为 id...”

我做错了什么?

问候...

【问题讨论】:

  • 已经检查过了,但没有回答这个问题......在我的例子中,“stats”已经是一个 Mongo 文档,所以,根据文档,我可以保存它而不是必须先创建另一个文档。

标签: node.js mongodb mongoose


【解决方案1】:

最后,更新承诺给 Model 而不是 mongoose.Schema 的统计类型:

        this.statsModel.findOne(
            {product_id: requestData.ean},
        ).then((stats: Model<Stats>) => {
            const productId: string = requestData.ean;
            // Update stats with the new scan...
            const beforeStats: mongoose.Schema = stats;

            const scan: any = {
                coords: {
                    lat: requestData.lat,
                    lon: requestData.lon,
                },
                at: new Date(),
            };

            if (stats) {
                stats.scans.push(scan);
                stats.save();
            } else {
                const newStat = new this.statsModel();
                newStat._id = requestData.ean;
                newStat.product_id = requestData.ean;
                newStat.scans = [scan];
                newStat.purchases = [];
                newStat.save();
            }

所以 save() 方法可以正常工作...

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2015-02-19
    相关资源
    最近更新 更多