I'm new to nodejs and mongodb. Can someone explain the behaviour of the following code to me?
var express = require('express')
var app = express();
var MongoClient = require('mongodb').MongoClient
const assert = require('assert')
const mongourl = 'mongodb://localhost:27017/test'
var str=""
MongoClient.connect(mongourl, function(err, client){
assert.equal(null, err);
var db = client.db('test');
var cursor = db.collection('projects.testproject.exampleChannel.germany.parameter').find();
cursor.forEach(function(item){
if(item!=null){
str=str+JSON.stringify(item)
console.log("1 "+str)
}
})
client.close();
console.log("2 "+str)
})
I get the following output and don't understand, why output 1 is what I expected and output 2 is empty.
2
1 {"_id":"5e67960fd92ba91300f5d718","basicInfo":{"projectName":"exampleProject","salesChannel":"exampleChannel","country":"germany"},"categories":{"pieceItems":{"amount":0},"weightItems":{"amount":0},"lengthItems":{"amount":0},"volumeItems":{"amount":0},"weightCodedItems":{"amount":0},"lengthCodedItems":{"amount":0},"volumeCodedItems":{"amount":0},"priceCodedItems":{"amount":0},"deposit&containerItems":{"amount":0},"ageRestrictedItems":{"amount":0},"prepaidItems":{"amount":0},"e-loadingItems":{"amount":0},"guranteeItems":{"amount":0},"paperReadingItems":{"amount":0},"technicalItems":{"amount":0},"giftItems":{"amount":0},"commonCustomerCardItems":{"amount":0},"payBackCardItems":{"amount":0},"deutschlandCardItems":{"amount":0},"serviceItems":{"amount":0}}}
.find()is anasyncoperation and subsequently.forEachtakes a callback function to get you results. The execution is not going to wait for that loop to finish off before reachingconsole.log("2 "+str)