簡體   English   中英

我得到一個 save() is a not a function error 貓鼬

[英]I get a save() is a not a function error mongoose

exports.clearHours = (req, res, next) => {
    Hour
    .find({ user: req.body.userId })
    .then(hour => {
        for (let i=0;i<hour.length;i++) {
            hour[i].hours = 0;
        }
        return hour.save()
    })
    .then(result => {
        res.status(200).json({message: 'Working hours have been successfully updated.'});
    })
    .catch(err => {
        if (!err.statusCode) {
            err.statusCode = 500;
        }
        next(err);
    })
};

我正在嘗試將格式化的數組保存在數據庫中,但出現此錯誤。 更新的代碼正確傳遞,但是當我嘗試保存數組時,它出現了這個錯誤。 任何想法為什么?

這是我的小時模型:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const hourSchema = new Schema ({
    day: {
        type: String,
        required: true
    },
    hours: {
        type: Number,
        required: true
    },
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }
});

module.exports = mongoose.model('Hour', hourSchema);

看來您正在將文檔提取到內存中並將hour字段重新設置為 0,您最好可以對數據庫本身運行更新查詢。

最重要的是需要貓鼬 -

const mongoose = require('mongoose');

下面是重構的clearHours方法。

exports.clearHours = async (req, res, next) => {
    try {
        const query = { 
            user: mongoose.Types.ObjectId(req.body.userId)
        };
        const update = {
            $set: {
                hours: 0
            }
        };
        await Hour.update(query, update).exec();
        res.status(200).json({message: 'Working hours have been successfully updated.'});
    } catch (err) {
        if (!err.statusCode) {
            err.statusCode = 500;
        }
        next(err);
    }
};

暫無
暫無

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

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