MongoDb和NodeJs //将数据从DB存储到变量

时间:2018-02-03 16:29:22

标签: node.js mongodb mongoose

更新:第一次回答后我意识到应该澄清一下。我需要从db中检索来自2个不同文档的数据并进行比较。所以我在想解决方案,似乎找到了它。

我的问题是:

我是NodeJs和MongoDb的新手,我试图将从mongoDb收到的数据设置为变量:

let variableToStoreData1;
let variableToStoreData2;

db.collection('costs').find({}).toArray(function(err, result) {
   console.log('result', result[0].user.last_name);
   variableToStoreData1 = result;
});

db.collection('messages').find({}).toArray(function(err, result) {
   console.log('result', result[0].user.last_name);
   variableToStoreData2 = result;
});

console.log(variableToStoreData1) // undefined
console.log(variableToStoreData2) // undefined

我的解决方案     let variableToStoreData1;     let variableToStoreData2;

db.collection('costs').find({}).toArray(function(err, result) {
  console.log('result', result[0].user.last_name);
  variableToStoreData1 = result;
});

db.collection('messages').find({}).toArray(function(err, result) {
 console.log('result', result[0].user.last_name);
 variableToStoreData2 = result;
 callback();
});

function callback () {
  console.log(variableToStoreData1) // now it's defined
  console.log(variableToStoreData2) // now it's defined
}

1 个答案:

答案 0 :(得分:0)

那是因为你在设置之前打印变量。打印时variableToStoreDataundefined,当db.find的响应到达时,您将其设置为几毫秒。

let variableToStoreData;

db.collection('costs').find({}).toArray(function(err, result) {
   console.log('result', result[0].user.last_name);
   variableToStoreData = result;
   callback()
});

function callback() {
   console.log(variableToStoreData) // now it's not undefined
}