如何正确处理猫鼬CRUD的错误

时间:2021-08-21 02:35:53

I am building a very simple RESTFUL app to see how Node and Mongo work together.

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

A made a function to find a "Persona" document on a mongodb by Id, so here is the code:

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);
        }

    })


}

And I use this route, where function is executed:

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

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

So, when I pass as parameter a valid ID, everything is ok, I get the proper Persona object in the response.

所以,当我作为参数传递一个有效的ID时,一切正常,我在响应中得到了正确的Persona对象。

But when I use a not valid ID (no document with that ID exists on the mongodb), the error specified on the exec callback is thrown... but, isn´t supossed that this error should be thrown only in case there are server problems? a non existent ID should not be a 500 error, isn´t it?

但是当我使用一个无效的ID(mongodb上没有该ID的文件)时,会抛出exec回调中指定的错误...但是,并不认为只有在有服务器的情况下才会抛出此错误问题?一个不存在的ID不应该是500错误,不是吗?

I looked for info and I found this:

我找了信息,我发现了这个:

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

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);
});

And reading the commented lines on the code above, confuses me even more... the error, as said in those comments, should be an error database or something similar, not a "not found" error... but the error is actually thrown when an object with that ID is not found!

阅读上面代码中的注释行,让我更加困惑......正如那些评论中所说的那样,错误应该是一个错误数据库或类似的东西,而不是“未找到”的错误...但错误实际上是找不到具有该ID的对象时抛出!

This is the error I get with a non valid 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"
}

2 个解决方案

#1


1  

As you are using mongoose, you can validate that the incoming value is an objectId or not by using mongoose.Types.ObjectId.isValid(req.params.id). This will return a boolean and possibly save you some effort or writing the regex for object Id validation.

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

#2


1  

You have defined your _id as ObjectId in schema. Not every string is a valid ObjectId. the id tha you are passing to findById is not valid. Object id should be 24 characters long string. Add this check before querying,

您已在架构中将_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
}

or if you want to keep using any string as _id, define _id as String instead of ObjectId in your schema.

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

#1


1  

As you are using mongoose, you can validate that the incoming value is an objectId or not by using mongoose.Types.ObjectId.isValid(req.params.id). This will return a boolean and possibly save you some effort or writing the regex for object Id validation.

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

#2


1  

You have defined your _id as ObjectId in schema. Not every string is a valid ObjectId. the id tha you are passing to findById is not valid. Object id should be 24 characters long string. Add this check before querying,

您已在架构中将_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
}

or if you want to keep using any string as _id, define _id as String instead of ObjectId in your schema.

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