node.js - 如何在快速路由参数、猫鼬中按名称及其 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 参数
如何区分这个
解决方案
你不能。对于 Express,两条路线是相同的(给变量赋予不同的名称在这里不起作用)。
您需要使用上述任一路线,并且需要修改逻辑以查找product
数据。
router.get("/:id_or_name", async (req, res, next) => {
获取此id_or_name
变量的值并检查它是否有效ObjectId
is 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 ...
推荐阅读
- jmeter - JMeter“验证脚本” - 我应该在“结果树”中看到什么?
- ckan - ckan 2.9.0 iroute before_map 不调用自定义控制器
- python - ColumnDataSource 的 on_change 事件的 Bokeh Old 和 New 参数具有相同的值
- json - 在角度 7 中将对象转换为 json
- c# - 在 C# 中接受来自控制台应用程序的输入,而不是使用 Console.ReadLine()
- spring-data-jpa - Spring Data JPA 更新:首选方式
- javascript - JS 通过深度嵌套的对象减少和分组 JSON
- xamarin.forms - 从 PCL 项目调用 xamarin.ios 中的方法
- c# - 上传到 arduino C#
- php - htmlentities() 似乎没有工作