node.js - 转换为 ObjectId 的值失败......在模型的路径“_id”,但我没有做任何查询
问题描述
我有一条从前端通过 axios 调用的快速路由。问题是,无论我在路线中添加什么,我总是会遇到同样的错误:
“模型“本地”的路径“_id”处的值“getTodosMisProductos”转换为 ObjectId 失败”
我没有对该路线中的猫鼬进行任何查询,但在我进行查询的任何其他路线中,一切正常。
我检查了中间件,但没有对 mongoose 的任何查询
getTodosMisProductos
router.get("/getTodosMisProductos", auth, async (req, res) => {
/*
try {
const data = await Local.findOne({ user: req.user.id }).populate("products.producto");
console.log(data);
if (!data) {
return res
.status(404)
.json({ errors: [{ msg: "No se encontro el local" }] });
}
return res.status(200).json(data.products);
} catch (error) {
console.log(req.user.id);
console.error("error en llamado");
return res.status(500).send("Server Error");
}
*/
console.log("algo");
return res.status(200).json({ msg: "success" });
});
注释的代码是我需要使用的代码,我出于测试目的对其进行了更改,但即使使用那个简单的新代码,我也会遇到同样的错误。
授权中间件
const jwt = require("jsonwebtoken");
const config = require("config");
module.exports = function (req, res, next) {
// Get token from header
const token = req.header("x-auth-token");
// Check if not token
if (!token) {
return res
.status(401)
.json({ msg: "No tienes autorización para hacer esto" });
}
// Verify token
try {
const decoded = jwt.verify(token, require("../config/keys").jwtSecret);
req.user = decoded.user;
next();
} catch (error) {
res.status(401).json({ msg: "El token es inválido" });
}
};
调用路由的操作
export const getAllProductos = () => async (dispatch) => {
try {
console.log("Esto se llama");
const res = await axios.get("/api/local/getTodosMisProductos/");
dispatch({
type: SET_PRODUCTS,
payload: res.data,
});
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, "danger")));
}
}
};
响应状态始终为 500(内部服务器错误)
编辑
//@route GET api/local/:id
//@desc obtener local por id
//@access private
router.get("/:id", auth, async (req, res) => {
try {
const local = await Local.findById(req.params.id);
if (!local) {
return res
.status(404)
.json({ errors: [{ msg: "No se encontro el local" }] });
}
return res.status(200).json(local);
} catch (error) {
console.error(error.message);
res.status(500).send("Server Error");
}
});
解决方案
您还有另一条路线也匹配/api/local/getTodosMisProductos/
显然它与/api/local/:id
,
你在哪里得到req.params.id = "getTodosMisProductos"
并被传到哪里await Local.findById(req.params.id)
并且 mongoose 无法转换"getTodosMisProductos"
为ObjectId
,因此出现错误。
声明路由的顺序会影响匹配的优先级。
顺序是先到先得,因此请确保在声明之前声明/api/local/addProducto
或任何其他以开头的路线/api/local/
/api/local/:id
推荐阅读
- c++ - 嵌套循环 OpenMP 并行化、私有或公共索引?
- google-sheets - Google 电子表格 - 来自另一个工作簿的 VLookup 值
- vhdl - rising_edge() 与进程敏感度列表
- android - 领域将 where 子句应用于 innerRealm 列表
- javascript - 无法用视频帧填充表格
- reactjs - 开玩笑的单元测试,如何解决异步功能
- opencv - 如何使用 OpenCV 从建筑楼层的顶部布局中查找墙壁、柱子、梁、门、窗和房间的位置和尺寸?
- c - c-在主程序中使用不同的共享库并在程序中加载
- html - 无法从类型“文件”输入中更改侧面文本
- awk - 删除文件中的每一个匹配项