【发布时间】: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: null 和programId: '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 });
但是,我无法使用 .then 和 res 访问它,也许我在语法上犯了错误,但我们将不胜感激。
【问题讨论】:
-
您的问题可能来自
.then您没有将函数传递给 then 函数。更新它,使其显示为.then(res => {/* code that's there now*/}
标签: javascript node.js mongodb asynchronous async-await