好吧,我现在已经挣扎了一段时间(或者说我的脑袋会爆炸......)。我在Node.js编写了一个简单的应用程序,允许用户为学生分配幸运镜头(吸虫)。我遇到问题的功能是获取学生=>侥幸点图。
我使用的是Express 4.15.5和Mongoose 5.0.1。
这是我的代码:
router.get('/list', (request, response) => {
Fluke
.find({})
.then((flukes) => {
response.render('pages/fluke/list', { tableData: aggregateStudentsWithFlukes(flukes) })
})
})
function aggregateStudentsWithFlukes(flukes) {
let result = new Map()
flukes.forEach((fluke) => {
let points = fluke.acquiredPoints
Student
.findById(fluke.student)
.then((student) => {
let studentName = getStudentName(student.name, student.surname)
if (result.has(studentName))
result.get(studentName).push(points) /* Exists, push points */
else
result.set(studentName, [points]) /* Doesn't exist, create new one */
})
})
return result
}
我希望地图看起来像这样:
{
'Name Surname': [25, 15, 30]
...more entries...
}
但我继续得到一张空地图。我该如何解决这个问题?
答案 0 :(得分:0)
你拥有的一切似乎都是正确的,我尝试模拟类似的东西,它完美地运行下面的代码。
function populatePoints(name, point) {
let result = new Map();
if (result.has(name)) {
result.get(name).push(point)
} else {
result.set(name, [point])
}
return result
}
console.log(populatePoints('John Doe', 22));
console.log(populatePoints('John Doe', 22));
console.log(populatePoints('Jenny Doe', 29));
但是,在promise
被调用之前,您的return result
尚未解决,这就是您获取空对象的原因。
因此,请尝试将return
语句移至Student.findById(fluke.student).then((student)
承诺
更像这样
Student
.findById(fluke.student)
.then((student) => {
let studentName = getStudentName(student.name, student.surname)
if (result.has(studentName)) {
result.get(studentName).push(points) /* Exists, push points */
} else {
result.set(studentName, [points])
}
return result;
})