Cast to ObjectId failed for value "search" at path "_id" for model "Order"

Cast to ObjectId failed for value "search" at path "_id" for model "Order"

  • Cast to ObjectId failed for value "search" at path "_id" for model "Order"
    • 解决方法:

Cast to ObjectId failed for value “search” at path “_id” for model “Order”

在使用express + mongoose开发商场应用时,在后台管理系统中筛选订单信息,突然出现下面这种错误:
Cast to ObjectId failed for value
错误信息为在模型“Order”的路径“ _id”处,“search”强制转换为ObjectId失败。

代码如下:

//查找 订单 根据查找条件
router.get('/orders/search', async (req, res) => {
  try {
    let params = {};
    const { title, status = 0 } = req.query;
    if (title) {
      params['title'] = title;
    }
    const orders = await Order.find(params, { updateTime: 0 }).populate('user', 'name').populate('book', 'name image price').exec();
    const total = await Order.countDocuments();
    return res.send({
      code: 200,
      result: {
        total,
        orders
      }
    });
  } catch (error) {
    console.log(error);
  }
});

最后发现,上一个接口的路径为**/orders/:id**,并在此接口中使用findById的方法查询。而在请求serch这个接口时,"search"作为id的值,在调用findById时就会出错。

解决方法:

  1. 修改接口路径,如将"/orders/:id"改为“/orders/details/:id”
  2. 调用mongoose的API,isValidObjectId判断一个值是否为ObjectId的类型
if (isValidObjectId(val)){
	...代码
}

你可能感兴趣的:(Express,MongoDB)