【问题标题】:NodeJS/ExpressJS api findById returns nullNodeJS/ExpressJS api findById 返回 null
【发布时间】:2021-10-30 02:00:47
【问题描述】:

这是我在控制器中的代码

const getById = async (req, res) => {
  try {
    const myId = Inventory.findById(id).exec();
    res.json(myId);
  } catch (error) {
    res.json({
      message: error
    });
  }
};

我的路由器

 router.get('/details/:id', homeController.getById);

【问题讨论】:

  • 您可能需要将您的 id 转换为 ObjectId 的类型。
  • 您是否尝试在您的getById 函数中使用req.params.id 而不是id

标签: node.js express mongoose rest


【解决方案1】:

你有问题。首先是您没有等待findById() 返回结果。您应该等待它,然后返回响应。其次是您正在传递未定义的id。您应该改为传递req.params.id

const myId = await Inventory.findById(req.params.id).exec();

【讨论】:

  • 您好 Nenad,感谢您与我们联系,我添加了 await,但仍然得到相同的结果
【解决方案2】:

您得到一个空结果,因为它在处理请求之前就返回了响应。看起来你在这里需要一个 Promise 或 Callback 以及你试图传递的 id 在哪里。我对您的设置做了很多假设,所以如果这不起作用,请详细说明您的问题

例子

const getById = async (req, res) => {
    // We need the id we are going to pass from the request
    id = req.body.id;
    try {
        // Because nodejs is asyncronise we need to add a block such as a promise
        async function info() {
            data = new Promise((resolve, reject) => {
                var info = Inventory.findById(id).exec();
                resolve(info);
            })
            return await data;
        }
        // now we can call the promise and wait for the response before we send the json
        const myId = await info();
        res.json(myId);
    } catch (error) {
        res.json({
            message: error
        });
    }
};

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
  • 我很高兴听到这个消息!如果您满意,您介意点击接受的答案吗?需要代表点。哈哈!度过一个愉快的夜晚。
猜你喜欢
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 2016-07-01
  • 2017-06-24
相关资源
最近更新 更多