首页 > 解决方案 > 如何在快速路由参数、猫鼬中按名称及其 id 获取数据

问题描述

通过id查找数据,这样的路由参数

网址是:http://localhost:8000/products/60d1789867bc6624403ade6e

// getting a single product
router.get("/:id", async (req, res, next) => {
const id = req.params.id;
try {
    const result = await Product.findById(id);
    return res.json({
    result,
  });
  } catch (error) {
     return res.status(400).json({
     msg: "product not found",
     error: error,
  });
 }
});

但是当我尝试按名称 url 查找时:http://localhost:8000/products/product_name

// getting products by name
  router.get("/:name", async (req, res, next) => {
  const name = req.params.name;
  try {
      const result = await Product.find({ name: name });
      return res.json({
      result,
   });
   } catch (error) {
       return res.status(400).json({
       msg: "product not found",
       error: error,
    });
   }
  });  

此代码块不执行,url req 转到 :id 参数

如何区分这个

标签: node.jsapiexpressrest

解决方案


你不能。对于 Express,两条路线是相同的(给变量赋予不同的名称在这里不起作用)。

您需要使用上述任一路线,并且需要修改逻辑以查找product数据。

router.get("/:id_or_name", async (req, res, next) => {

获取此id_or_name变量的值并检查它是否有效ObjectIdis not using mongoose.Types.ObjectId.isValid()。如果有效,则执行.findById()else go for.find()方法。

const id_or_name = req.params.id_or_name;

// ... code ...
if (mongoose.Types.ObjectId.isValid(id_or_name)) {
  result = await Product.findById(id_or_name);
} else {
  result = await Product.find({ firstName: id_or_name });
}
// ... code ...

推荐阅读