CastError: Cast to ObjectId failed for value "XXXXXXXXXX" (type string) at path "_id" for model "XXXX"

CastError: Cast to ObjectId failed for value "XXXXXXXXXX" (type string) at path "_id" for model "XXXX"

我是初学者。

当我用错误的(短)ID 测试路线时,例如我放置 "6261220286e8d5e7ee6f221" 而不是 "6261220286e8d5e7ee6f221e" 节点应用程序崩溃并出现此错误:

这是路线代码:

router.put('/:id', async (req, res) => {
    //Validate with Joi
    const { error } = validateGenre(req.body);
    //If invalid, return 400 - Bad Request.
    if (error) return res.status(400).send(error.details[0].message);
    //Look up the genre and Update.
    const genre = await Genre.findByIdAndUpdate(req.params.id, { name: req.body.name }, { new: true })
    //If not exists, return 404.
    if (!genre) return res.status(404).send('The genre with the given ID was not found');
    //Return ubdated genre.
    res.send(genre);
});

function validateGenre(genre) {
    const schema = Joi.object({ name: Joi.string().min(3).max(50).required() });
    return schema.validate(genre);
}

这里还有流派架构:

const genreSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50,
    }
});

const Genre = new mongoose.model('Genre', genreSchema);

我的问题是:如何处理此类错误,或者如何验证请求的 ID 长度以 return 向客户端发送正确的消息。

再次抱歉,我真的是初学者,在此先感谢。

您是否尝试过使用 try catch ??,在 catch 部分,您可以使用状态 500 和 Genre

抛出的错误消息进行响应