Node.js Mongoose findByIdAndUpdate不';如果找不到Id,则不会返回错误
我正在编写一个更新mongo DB数据的API。 当我传递一个不可用的ID时,它不会在Node.js Mongoose findByIdAndUpdate不';如果找不到Id,则不会返回错误,node.js,mongodb,express,mongoose,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, mod
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时,为什么不抛出错误。只需添加
如果(!model)返回res.status(404).send(“[404]:具有给定id的模型不存在”)
在返回模型之前
。为我工作只需添加
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;
}
}
如果(!model)返回res.status(404).send(“[404]:具有给定id的模型不存在”)
在
返回模型之前
。为我工作返回文档或null
-null
,以防找不到要更新的文档(这不是错误)。那么我应该使用什么来满足我的要求?要求是什么?如果没有id,那么它应该返回error
no id found您可以检查null并执行应用程序应该执行的操作。比如,给用户的一条消息,可能说文档不存在,无法更新。返回文档或null
-null
,以防找不到要更新的文档(这不是错误)。那么我应该使用什么来满足我的要求?要求是什么?如果没有id,那么它应该返回error
找不到id。您可以检查null并执行应用程序应该执行的操作。比如,给用户的一条消息,可能说文档不存在,无法更新。
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;
}
}