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

时间:2022-10-05 02:34:54

This question already has an answer here:

这个问题在这里已有答案:

UPDATE: After first answerI realized that should clarify. I need to retrieve data from 2 different documents from db and compare them. So I was thinking about solution and seems to find it.

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

My question was:

我的问题是:

I'm new in NodeJs and MongoDb and I'm stuck trying to set data received from mongoDb to variable:

我是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

My solution let variableToStoreData1; let variableToStoreData2;

我的解决方案让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 个解决方案

#1


0  

That's because you print the variable before you set it. The variableToStoreData is undefined when you print it and you set it a few millisecond later when the response from db.find arrive.

那是因为你在设置之前打印变量。当您打印它时,variableToStoreData是未定义的,并且当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
}

#1


0  

That's because you print the variable before you set it. The variableToStoreData is undefined when you print it and you set it a few millisecond later when the response from db.find arrive.

那是因为你在设置之前打印变量。当您打印它时,variableToStoreData是未定义的,并且当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
}