【发布时间】:2020-09-22 10:01:36
【问题描述】:
app.get('/allColleges', (req, res) => {
collegeModel.find().sort({ field: 'asc', _id: -1 }).exec((err, colleges) => {
if (!colleges || colleges.length === 0) {
return res.status(200).json(null)
} else {
var collegedata = Array.from(colleges)
for (i = 0; i < collegedata.length; i++) {
var collegeGalleryData = {};
var collegeGallery = collegeGalleryModel.find({collegeId: collegedata[i]._id}, (err, collegeGallery) => {
if (!collegeGallery || collegeGallery.length > 0){
collegeGalleryData.data = collegeGallery;
}
})
collegedata[i].collegeGallery = collegeGalleryData.data;
}
}
return res.json(collegedata)
})
})
我在 Express JS 中创建了一个 API。在这个 API 中,我需要查询结果传递到的回调函数之外的集合中的数据。
我创建了一个对象变量并在回调函数中添加了一个键“数据”,并尝试将其值设置为使用collegeGalleryModel 在第二个查询中找到的数据。
当我在回调函数outside这个对象中检查data 的值时,它是空的。
那么,我们怎样才能得到传递给回调函数外部回调函数的结果值呢?
【问题讨论】:
-
你在用猫鼬吗?
-
尝试在查询中使用 async/await api 而不是回调
标签: node.js mongodb express callback