MongoDB查询上的Node.js异步映射 [英] Node.js async map over MongoDB queries

查看:96
本文介绍了MongoDB查询上的Node.js异步映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在async Node.js模块上遇到问题.在我的Node.js应用中,我试图获取MongoDB请求返回的JSON对象数组:

I'm having a problem with async Node.js module. In my Node.js app, I'm trying to get an array of JSON objects returned by a MongoDB request:

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); // -> []

此刻,我在这里.

我正在尝试实现async.map以遍历Fruits集合. https://caolan.github.io/async/docs.html#map

I'm trying to implement the async.map to iterate through Fruits collection. https://caolan.github.io/async/docs.html#map

有人可以帮忙吗? :)

Can someone help? :)

在此先感谢您的帮助.

因为我需要db.collection函数返回的所有结果,所以我试图将这些异步命令添加到队列中,执行并获取回调函数.

As I need all results returned by my db.collection functions, I'm trying to add these async commands to a queue, execute it and get a callback function.

推荐答案

您可以尝试以下操作:

async.map(fruits , function (fruit, callback) {
    db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {        
        //here you are assigning value as array property         
        //finalTab[fruit] = result;
        // but you need to push the value in array
        finalTab.push(result);
        console.log(result); // -> display the desired content
        db.close();
        if (err) throw err;
        //callback once you have result
        callback();
    }));
}.bind(this), function () {
    console.log(finalTab); // finally call
}, function (err, result) {
    return Promise.reject(err);
});

这篇关于MongoDB查询上的Node.js异步映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆