如何将查询结果推送到node.js中的数组变量?

时间:2019-04-25 12:28:47

标签: javascript arrays node.js mongodb loops

我正在使用Node.js和MongoDB地图集,这是一个在线数据库。我已经建立了与MongoDB地图集的连接,并向数据库发送了一个查询并检索了一个集合。集合返回没有任何错误。现在,我试图将查询结果推到一个数组,但该数组仍然为空。

我尝试使用console.log(),发现循环后该数组变为空。我注意到第二个console.log之前已打印。我不知道为什么。

<FlatList data={this.state.data} extraData={this.state} .../>

3 个答案:

答案 0 :(得分:1)

toArray是异步的-您正在console.toArray调用之前记录空数组。试试这个:

const mongoose = require('mongoose');

var data = async function () {

    const array = await mongoose.connection.collection("organizations").find({}).toArray(function(err, result) {
        if (err) throw err;
        return result.map(r => r.name);
    });

    console.log(array); //this shows only [] meaning that the array is now empty.
                        //this is shown in the log before the first log
    return array;
};

module.exports = {
    data: data,
};

答案 1 :(得分:1)

从表创建连接和获取信息是异步操作。完成请求可能需要一些时间。因此,您可以使用async/awaitpromise来处理异步操作,如下所示。

const mongoose = require('mongoose');
    var data = async function () {
         var array = [];
         const finalResults = await new Promise((resolve, reject) => {
            mongoose.connection.collection("organizations").find({}).toArray(function(err, result) {
              resolve(result);
           });
      });

     for(var i = 0; i < finalResults.length; i++)
     {
          var a = finalResults[i].name;
           array.push(a);
      }
        return array;
    };

    module.exports = {
        data: data,
    };

这可能会对您有所帮助。

答案 2 :(得分:0)

您无法从异步回调中返回,这里.toArray()是回调。

因此,修改您的代码以传递可以发送结果的回调函数。

假设此内容写在mongooseModule.js

const mongoose = require('mongoose');

var data = function (callback) {

    var array = [];

    mongoose.connection.collection("organizations").find({}).toArray(function(err, result) {
        if (err) throw err;

        for(var i = 0; i < result.length; i++)
        {
            var a = result[i].name;
            array.push(a);
            console.log(array[i]); //this shows that the array is getting filled and the result is printed correctly.
        }

        callback(array);
    });
};

module.exports = {
    data: data,
};

在您的Express处理程序中:

const mongooseModule = require('mongooseModule'); 

app.get('/someroute', function(req, res, next) {
    res.status(200);
    mongooseModule.data(res.json);
});
相关问题