【问题标题】:Populate an array with multiple mongo queries [duplicate]使用多个 mongo 查询填充数组 [重复]
【发布时间】:2018-07-31 01:39:09
【问题描述】:

我遇到了回调混乱的问题。

在我的 nodejs 应用程序中,我试图获取由 mongoDB 请求返回的 JSON 对象数组。我不知道为什么,但它没有按我的意愿填充。

我怀疑异步结果/回调混乱的问题。

var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit) {
    db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {                 
        finalTab[fruit] = result;
        console.log(result); // -> display the desired content
        db.close();
        if (err) throw err;
    }));
});
console.log(finalTab); // -> []

提前感谢您的帮助。

编辑: 因为我需要我的 db.collection...functions... 返回的所有结果...我正在尝试将这些异步命令添加到队列中,执行它并获取回调函数。 我认为异步 nodejs 模块可以提供帮助。

有人可以告诉我如何在 ForEach() 中执行此操作吗?

【问题讨论】:

标签: node.js mongodb asynchronous mongoose callback


【解决方案1】:

finalTab[fruit] = result; 行将无济于事,因为fruit 没有索引。您需要在forEach() 中使用索引,如下所示 -

var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit, index) {
    db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {                 
        finalTab[index] = result;
        console.log(result); // -> display the desired content
        db.close();
        if (err) throw err;
    }));
});
console.log(finalTab); // -> []

【讨论】:

  • 虽然这是朝着正确方向迈出的一小步,但您的代码仍然存在多个问题。
  • 是否可以将fruit变量的内容用作数组的键?像这样 -> [ 'Peach' => {myobject}, 'Banana' => ....etc ]
  • 我编辑了我的问题 Patrick。你能帮忙吗?
猜你喜欢
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2016-03-03
  • 1970-01-01
  • 2012-06-06
  • 2018-05-07
  • 1970-01-01
相关资源
最近更新 更多