【问题标题】:How to access the response from .find in a JSON object with Node.js如何使用 Node.js 从 JSON 对象中的 .find 访问响应
【发布时间】:2020-08-06 13:09:51
【问题描述】:

我有一个“伪”数据库,类似于 MongoDB 中具有 JSON 对象的集合。

export const roles = [
  { 
    _id: "870c4350-3cf5-4f35-8429-513bd86c6734",
    programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968",
    profileId: "3cbaadcf-41e1-423b-aa6a-b3fb401df148",
    fullName: null,
    jobTitle: "Regional Implementation Executive",
    department: "Electronics",
    favouriteColour: "salmon",
  },
  {
    _id: "ed231d80-f22b-4f52-bd94-9d58a2fbdbc8",
    programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968",
    profileId: "1bc21aff-896f-44da-8436-a1604a626c39",
    fullName: null,
    jobTitle: "Direct Identity Strategist",
    department: "Beauty",
    favouriteColour: "silver",
  },
  {
    _id: "c6804099-150f-401b-9e3d-15945085fdde",
    programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968",
    profileId: "580acb22-46f1-4bc3-b74f-606c933e43a0",
    fullName: null,
    jobTitle: "Investor Brand Developer",
    department: "Garden",
    favouriteColour: "cyan",
  },
  {
    _id: "45119579-ec48-4d7b-b4e3-656d2ad5468b",
    programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968",
    profileId: "98793f3f-2f03-49a8-b77e-e96e0eff1b28",
    fullName: null,
    jobTitle: "National Research Facilitator",
    department: "Home",
    favouriteColour: "turquoise",
  }
];

使用.find 我正在尝试使用fullName: nullprogramId: 'e3e20d57-571d-45ab-b13a-b07d29fcf968 获取所有项目。

这是我尝试使用.then() 访问响应的代码,因为.find 是一种异步方法。

  await roles.find({
        fullName: null,
        programId: 'e3e20d57-571d-45ab-b13a-b07d29fcf968'

      }).then((res.update(
        {
          programId: x._id,
        },
        {
          fullName: x.name,
        })
     ))
     .catch(err => console.log(err));

但是,我无法访问响应,因为我收到一条错误消息,提示 res is not defined

错误。

(node:99872) UnhandledPromiseRejectionWarning: ReferenceError: res is not defined
    at callback (/Users/Rahul/PersonalProjects/js-test/redact-surnames.js:28:20)
    at Object.forEach (/Users/Rahul/PersonalProjects/js-test/lib/collections.js:16:13)
    at _default (/Users/Rahul/PersonalProjects/js-test/redact-surnames.js:6:3)
(node:99872) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:99872) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我知道这个带有.find 的查询就像我将响应分配给const 然后console.log({ }); 我看到它打印正常。

const response = await roles.find({
    fullName: null,
    programId: 'e3e20d57-571d-45ab-b13a-b07d29fcf968'
  });
  console.log({ response });

但是,我无法使用 .thenres 访问它,也许我在语法上犯了错误,但我们将不胜感激。

【问题讨论】:

  • 您的问题可能来自 .then 您没有将函数传递给 then 函数。更新它,使其显示为.then(res => {/* code that's there now*/}

标签: javascript node.js mongodb asynchronous async-await


【解决方案1】:

如果您试图获取符合条件的角色内的所有项目

fullName === null && programId === 'e3e20d57-571d-45ab-b13a-b07d29fcf968'

您可以简单地使用过滤器来遍历数组并获得过滤后的结果。

这是一篇好文章:

https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d

但是如果你使用.find(),它会返回与传递的条件相对应的第一个值。你可以使用.find(),如果这是你所追求的。

const roles = [
  { 
    _id: "870c4350-3cf5-4f35-8429-513bd86c6734",
    programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968",
    profileId: "3cbaadcf-41e1-423b-aa6a-b3fb401df148",
    fullName: null,
    jobTitle: "Regional Implementation Executive",
    department: "Electronics",
    favouriteColour: "salmon",
  },
  {
    _id: "ed231d80-f22b-4f52-bd94-9d58a2fbdbc8",
    programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968",
    profileId: "1bc21aff-896f-44da-8436-a1604a626c39",
    fullName: null,
    jobTitle: "Direct Identity Strategist",
    department: "Beauty",
    favouriteColour: "silver",
  },
  {
    _id: "c6804099-150f-401b-9e3d-15945085fdde",
    programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968",
    profileId: "580acb22-46f1-4bc3-b74f-606c933e43a0",
    fullName: null,
    jobTitle: "Investor Brand Developer",
    department: "Garden",
    favouriteColour: "cyan",
  },
  {
    _id: "45119579-ec48-4d7b-b4e3-656d2ad5468b",
    programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968",
    profileId: "98793f3f-2f03-49a8-b77e-e96e0eff1b28",
    fullName: null,
    jobTitle: "National Research Facilitator",
    department: "Home",
    favouriteColour: "turquoise",
  }
];

// Using filter method
const filterResult = roles.filter((role)=> role.fullName === null && role.programId ==='e3e20d57-571d-45ab-b13a-b07d29fcf968');

// note: result here is an array of object/s
console.log(filterResult);


// Using find method
const findResult = roles.find((role)=> role.fullName === null && role.programId ==='e3e20d57-571d-45ab-b13a-b07d29fcf968');

// note: result here is an object
console.log(findResult);

【讨论】:

    【解决方案2】:

    我认为它导致了错误,

    await roles.find({
        fullName: null,
        programId: 'e3e20d57-571d-45ab-b13a-b07d29fcf968'
    
      }).then((res.update({  // <
        programId: x._id,    // <
      }, {                   // <
        fullName: x.name,    // <
      })))                   // <
      .catch(err => console.log(err));
    

    我想,你试图做这样的事情,

    .then(res =>
      res.update({
        programId: x._id
      }, {
        fullName: x.name
      })
    )
    

    【讨论】:

    • @RahulSam 如果有帮助,请考虑将其标记为答案 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2015-02-05
    • 2016-03-04
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多