0

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.

My question was:

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

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;

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
}
Dominic
  • 62,658
  • 20
  • 139
  • 163
Evgeny Ladyzhenskiy
  • 151
  • 1
  • 3
  • 15

1 Answers1

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.

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
}
Nikola Andreev
  • 624
  • 4
  • 18