将mongoose查询推送到node.js中的全局数组中

时间:2018-02-14 17:26:56

标签: node.js mongodb mongoose

我是nodejs和javascript的初学者。我想访问一个集合,然后将我检索到的查询存储到一个数组中,以便稍后我可以用该数组做更多的东西。 但是,当我将结果存储在数组中时,它不在函数外部。这是我的代码

const http = require('http');
const bodyParser = require('body-parser');
const locations = require('./models/vicitmsLocation');
const async = require('async');


var postcode = [];

locations.getAllTheIncidents({},function (err, results) {
if (err) {
    throw err;
} else {

    postcode.push(results);
    //Here the code works and array will be populated with data I want
    console.log(postcode);
} 
});
//Here it doesnt work and array is empty.
console.log(postcode);

我理解这可能是nodejs和mongo异步性质的问题,但我似乎无法弄清楚为什么会发生这种情况。

1 个答案:

答案 0 :(得分:0)

  

因为nodejs是非阻塞的,所以外部的console.log是   在locations.getAllTheIncidents的回调之前执行   被执行。

所以,你必须在回调中使用postcode或在promise中绑定locations.getAllTheIncidents

相关问题