簡體   English   中英

NodeJS Mongoose 更新文檔

[英]NodeJS Mongoose update document

我正在嘗試使用“mongoose”這種方式更新或創建 MongoDB 集合中的文檔:

        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 匹配的文檔...”

我在做什么錯?

問候...

最后,更新承諾給 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() 方法正常工作......

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM