【问题标题】:how to get data by name as well as its id in express route prameter, mongoose如何在快速路由参数猫鼬中按名称及其 id 获取数据
【发布时间】:2021-06-22 15:33:57
【问题描述】:

通过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,
  });
 }
});

但是当我尝试按名称查找时 网址: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.js api express rest


【解决方案1】:

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

您需要选择上述任一路线,并且需要修改逻辑以找到product 数据。

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

获取此id_or_name 变量的值并检查它是否是有效的ObjectId 未使用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 ...

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 2016-05-01
    • 2017-08-13
    • 1970-01-01
    • 2016-04-14
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多