如何将数据推送到数据库异步请求中的数组



我试图向数据库(mongoDB(发出请求,并将其返回保存在对象列表中,但该列表没有被填满。这是代码

router.get('/all/:studentEmail', auth, async (req, res) => {
try {
const student = await Student.findOne({ email: req.params.studentEmail });
if (!student) {
return res.status(404).json({ msg: 'Student not found' });
}
var list = [];
student.exercises.map(async (exercise) => {
list.unshift(await Exercise.findById(exercise));
});
res.json(list);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});

数据库查询await Exercise.findById(exercise)正确返回对象,但res.json(list);返回空。有人知道怎么解决吗?

基本问题是res.json()student.exercises.map(async (exercise) => {完成之前执行。将await放入map不需要等待异步循环中的每一项都得到处理。要么使用类似Promise.all()的东西,要么使用for循环(也可以使用其他策略(。根据您是可以并行处理还是需要串行处理来决定使用哪个。尝试使用Promise.all执行以下异步请求,并在每个Promise上使用then执行针对list的操作:

router.get("/all/:studentEmail", auth, async (req, res) => {
try {
const student = await Student.findOne({ email: req.params.studentEmail });
if (!student) {
return res.status(404).json({ msg: "Student not found" });
}
var list = [];
await Promise.all(
student.exercises.map((exercise) =>
Exercise.findById(exercise).then((result) => list.unshift(result))
)
);
res.json(list);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
});

此外,作为unshift的替代方案,如果它们没有嵌套,则只返回结果,如果它们是嵌套的,则可以考虑flat():

const list = await Promise.all(
student.exercises.map((exercise) => Exercise.findById(exercise))
);
return res.json(list);

希望这能有所帮助!

最新更新