异步瀑布返回节点 js 和 mongodb 中数组的单个记录

async waterfall return single record of array in node js and mongodb

本文关键字:mongodb 数组 记录 单个 js 节点 布返回 返回 异步      更新时间:2023-09-26

我正在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);
}