如何正确处理 mongoose CRUD 错误

How to properly handle error on mongoose CRUD

我正在构建一个非常简单的 RESTFUL 应用程序以了解 Node 和 Mongo 如何协同工作。

A 做了一个函数,通过 Id 在 mongodb 上查找 "Persona" 文档,所以这里是代码:

function getPersonabyId(req,res)
{
    //en params del objeto request esta lo que llega por get
    let idPersona=req.params.id;

    //mongoose trae un método para pillar por id
    Persona.findById(idPersona).exec((err,objPersona)=>
    {

        if(err)
        {
           res.status(500).send(err);
        }
        else{


            res.status(200).send(objPersona);
        }

    })


}

我使用这条路线,执行功能的地方:

miniApp.get("/getPersonaById/:id",controladorPersona.getPersonabyId);

因此,当我将有效 ID 作为参数传递时,一切正常,我在响应中获得了正确的 Persona 对象。

但是当我使用无效的 ID(mongodb 上不存在具有该 ID 的文档时),将抛出 exec 回调中指定的错误...但是,不应该是这个错误只有在服务器出现问题时才应该抛出?不存在的 ID 不应该是 500 错误,不是吗?

我查找了信息并找到了这个:

https://coursework.vschool.io/mongoose-crud/

Person.find((err, people) => {  
    // Note that this error doesn't mean nothing was found,
    // it means the database had an error while searching, hence the 500 status
    if (err) return res.status(500).send(err)
    // send the list of all people
    return res.status(200).send(people);
});

阅读上面代码中的注释行,让我更加困惑...如这些注释中所述,错误应该是错误数据库或类似的东西,而不是 "not found" 错误.. .但当找不到具有该 ID 的对象时,实际上会抛出错误!

这是我使用无效 ID 时遇到的错误:

{
    "message": "Cast to ObjectId failed for value \"5b105ba453401c41d0e3da2\" at path \"_id\" for model \"Persona\"",
    "name": "CastError",
    "stringValue": "\"5b105ba453401c41d0e3da2\"",
    "kind": "ObjectId",
    "value": "5b105ba453401c41d0e3da2",
    "path": "_id"
}

您已在架构中将 _id 定义为 ObjectId。并非每个字符串都是有效的 ObjectId。您传递给 findById 的 ID 无效。对象 ID 应为 24 个字符长的字符串。在查询之前添加此检查,

if (id.match(/^[0-9a-fA-F]{24}$/)) {
  // Yes, it's a valid ObjectId, proceed with `findById` call.
} else{
  //throw an error
}

或者如果您想继续使用任何字符串作为 _id,请在您的架构中将 _id 定义为 String 而不是 ObjectId

当您使用 mongoose 时,您可以使用 mongoose.Types.ObjectId.isValid(req.params.id) 验证传入值是否为 objectId。这将 return 一个布尔值,并可能为您节省一些精力或编写用于对象 ID 验证的正则表达式。