[英]NodeJS/MongoDB. Async/await returns the whole array of data
So, I try to understand why the Async/await in case of MongoDB returns some strange result, instead of the nedded by the condidtion? 因此,我试图理解为什么在MongoDB的情况下Async / await返回一些奇怪的结果,而不是受条件的束缚?
For example: I try to get the req.session.userId
from await
User.find()
, but always get the array of Users. 例如:我试图让
req.session.userId
从await
User.find()
但总是得到用户的阵列。
My code: 我的代码:
.get((req, res) => {
let a = '';
async function userFind() {
const sess = await User.find((err, users) => {
if (req.session.userId !== undefined) {
return req.session.userId; // return the all array ou Users, instead of just session value
}
else {
return "req.session.userId"; // return the all array of Users, instead of just a string
}
});
console.log(sess);
const empl = await EmployersSchemaDB.find((err, employers) => {
return employers;
});
return {
sess,
empl
}
}
console.log(userFind()); // gives two arrays of data above together, but not that I want...
})
You have to await
the userFind()
function. 您必须
await
userFind()
函数。
The way async functions work is that they return a promise. 异步功能的工作方式是它们返回承诺。 You are awaiting the DB accesses inside of userFind() but you are not awaiting userFind() itself.
您正在等待userFind()内部的数据库访问,但不是在等待userFind()本身。
.get(async (req, res) => {
let a = '';
async function userFind() {
const sess = await User.find((err, users) => {
if (req.session.userId !== undefined) {
return req.session.userId; // return the all array ou Users, instead of just session value
}
else {
return "req.session.userId"; // return the all array of Users, instead of just a string
}
});
console.log(sess);
const empl = await EmployersSchemaDB.find((err, employers) => {
return employers;
});
return {
sess,
empl
}
}
console.log(await userFind()); // gives two arrays of data above together, but not that I want...
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.