如果找不到ID,猫鼬findByIdAndUpdate不会返回错误

时间:2020-07-02 08:40:04

标签: node.js mongodb express mongoose

我正在编写一个用于更新mongo DB数据的API。 当我传递一个不可用的ID时,它不会在findByIdAndUpdate处引发错误。而是返回空白结果。

const update_data = async(data) => {

    try {

        const res = customReportModel.findByIdAndUpdate(data.input._id, data.input.body, {new: true}, function(err, model) {
            if(err) {
                console.error(error);
                const e = new Error(`Data with ${data.input._id} not found.`);
                throw e;
            }
            return model;
        })


    } catch (error) {

        console.error(error);
        const e = new Error('Error while updating.');
        throw e;
    }

}

不确定数据库中不存在ID时为什么不引发错误。

2 个答案:

答案 0 :(得分:0)

只需添加 if(!model) return res.status(404).send('[404]: Model with given id does not exist')return model 之前。为我工作

答案 1 :(得分:0)

const update_data = async(data) => {

    try {

        const res = customReportModel.findByIdAndUpdate(data.input._id, data.input.body, {new: true}, function(err, model) {
            if(!model) {
                const e = new Error(`Data with ${data.input._id} not found.`);
                throw e;
            } else{
                return model;
            }
        })
    } catch (error) {
        console.error(error);
        const e = new Error('Error while updating.');
        throw e;
    }

}
相关问题