异步瀑布返回节点 js 和 mongodb 中数组的单个记录
async waterfall return single record of array in node js and mongodb
我正在nodejs和mongodb和angularjs中创建chield和父类别菜单。我担心的是,当我使用回调返回推送数组时,尽管我有很多数据,但数组只包含一条记录。我不知道出了什么问题。这是我的代码。
async.waterfall([
function(cb) {
//getting the parent category
mealCatModel.find({
parentId: ''
}, {}, function(error, result) {
if (error) {
cb(error, null);
} else {
if (result) {
//loop through the record
result.forEach(function(key, value) {
//find the chield category on behalf of parent id and key.id
mealCatModel.find({
parentId: key._id
}, {}, function(err, subCat) {
if (subCat) {
subCat.forEach(function(k, v) {
if (k.parentId == key._id) {
// pushing all the record in a single array
mainJson.push({
mainCatId: key._id,
mainCatName: key.mealCatName,
subCatId: k._id,
subCatName: k.mealCatName
});
cb(null, mainJson);
}
})
}
})
})
} else {
cb('record not foound', null);
}
}
});
}
], function(error, mainJson) {
///return the err
if (error) {
res.json({
type: false,
data: 0
});
} else {
// return the array to front end
res.json({
type: true,
data: mainJson
});
}
});
第一个 find 函数获取主类别并依赖于我在键值对中循环的记录,然后我代表它找到了key._id,我再次运行具有主类别父级的 id 的查找查询。 因此,通过这种方式,我获得了我的Chield类别,然后在mainJson数组中推送数据。 但是当我返回 cb() 回调时,它只返回单个数组。
回调正在.forEach
中执行。在执行时,循环尚未完成其所有迭代。您应该重构代码以在.forEach
表达式之后返回回调:
if (subCat) {
subCat.forEach(function(k, v) {
if (k.parentId == key._id) {
// pushing all the record in a single array
mainJson.push({
mainCatId: key._id,
mainCatName: key.mealCatName,
subCatId: k._id,
subCatName: k.mealCatName
});
}
});
return cb(null, mainJson);
}
相关文章:
- MongoDB (php) - 以数组而不是多个属性的形式返回文档属性
- Mongodb$in以与数组中相同的顺序获取结果
- MongoDB-通过比较集合和对象的数组来返回现有字段的数组
- MongoDB数组与对象
- MongoDB嵌套对象数组后查询
- 如何在mongodb(mongose)中覆盖子文档的数组属性
- 如何获取文档数组中元素的计数-MongoDB
- 使用mongoose将数据推送到mongoDB模式中的数组中
- 如何在mongodb中根据数组内容的差异进行排序
- angular mongodb数组格式写错了
- node.js上的过程性2d数组mongoDB插入内存不足
- MongoDB findAndModify:>>>查找和更新文档数组中的对象
- 更新数组中的嵌入文档 - Mongodb + Node Driver
- mongodb数组重新排序和更新
- 如何删除mongodb数组中的元素
- 如何从 MongoDB 数组中删除重复的对象
- 使用Node.js操作Mongoose/MongoDB数组
- 最佳mongodb数组操作的性能
- AngularJS不显示MongoDB数组中的对象
- 不能更新或推送数据到mongodb数组