【问题标题】:Not able to map to values of the object inside an array fetched from mongodb无法映射到从 mongodb 获取的数组中的对象的值
【发布时间】:2021-09-09 21:25:32
【问题描述】:

当我在postman中获取值时,值为null,当我安慰titleArr时,它说obj.title的值是未定义的

obj.title 未定义

  router.get("/userID/:userId/title/", verify, async (req, res) => {
  const userIdParam = Number(req.params.userId);
  const postsObj = await PostsModel.find({ userId: userIdParam });
  const titleArr = postsObj.map((obj) => obj.title);
  res.send(titleArr);
});

【问题讨论】:

  • 尝试安慰postsObj(这将提示返回的数据是否确实是预期的)。如果结果不是预期的,请尝试安慰 req 对象本身,可能是 params 值不正确的情况?

标签: javascript node.js arrays mongodb mongoose


【解决方案1】:

这应该可以解决您的问题。

  router.get("/userID/:userId/title/", verify, async (req, res) => {
  const userIdParam = Number(req.params.userId);
  const postsObj = await PostsModel.find({ userId: userIdParam });
  const titleArr = postsObj.map((obj) => obj._doc.title); // <= Add _doc here
  res.send(titleArr);
});

说明:find方法返回model object的数组,其中包含_doc字段中的数据。

【讨论】:

    猜你喜欢
    • 2021-07-29
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2019-04-28
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多