首页 > 解决方案 > 转换为 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");
  }
});

标签: node.jsmongodbexpressmongoose

解决方案


您还有另一条路线也匹配/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


推荐阅读