【发布时间】:2020-02-09 11:12:19
【问题描述】:
在我的 Node Express 应用程序中,我想获取课程的所有 cmets,并通过在每个评论中添加 fullname 字段来修改每个评论。为了获取用户的全名,我在UserController.js 中定义了findFullNameByUserId 函数。我在CourseController.js 中使用findAllCommentsByLessonId(),如下所示。但是,当我使用它时,我总是得到一个空数组。如何在findAllCommentsByLessonId() 中使用findFullNameByUserId 以便将fullname 字段添加到每个评论对象?
CourseController.js
findAllCommentsByLessonId: async (courseId,lessonId,callback) => {
Course.find({_id: courseId}, function(err, course) {
if (err) {
callback(err, null);
} else {
const lesson = course[0].lessons.filter(l => l._id !== lessonId)
const comments = lesson[0].comments.map( async c => {
try{
const name = await UserController.findFullNameById(c.user)
return (
{
userId: c.user,
name: name,
content: c.content
}
)
}
catch(err){
console.log(err)
}
})
// console.log(comments) --> This always prints [{}]
callback(null, comments)
}
});
}
UserController.js
module.exports = {
findFullNameById: async (userId) => {
await User.find({_id: userId}, function(err, user) {
if (err) {
console.log(err)
} else {
return user[0].name+" "+( user[0].lname ? user[0].lname : "")
}
});
}
}
【问题讨论】:
-
数组方法
.map()、.filter()、.find()、.reduce()、.forEach()等不理解promise,因此不会等待异步函数。将for和while与await一起使用 -
你循环访问db,如果有很多cmet会导致性能问题。当您从 db 检索 cmets 时,您需要获取 FullName。我猜你正在使用猫鼬,所以你可以使用填充。
标签: javascript node.js express async-await