【问题标题】:push mongoose query into a global array in node.js将猫鼬查询推送到 node.js 中的全局数组中
【发布时间】:2018-07-25 08:50:47
【问题描述】:

总的来说,我是 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 的异步性质的问题,但我似乎无法弄清楚为什么会发生这种情况。

【问题讨论】:

  • 我不太明白这对我有什么帮助!
  • 由于异步特性,最后一个控制台在 getAllTheIncidents 回调返回数据之前执行。因此,如果您的下一个代码依赖于回调的结果,那么您必须在回调函数内部编写。

标签: node.js mongodb mongoose


【解决方案1】:

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

因此,您必须在回调中使用 postcode 或在 Promise 中绑定 locations.getAllTheIncidents

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2019-10-13
    • 2018-09-19
    • 2015-01-04
    • 1970-01-01
    • 2016-01-29
    • 2015-02-12
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多