Reputation: 41
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}}}
Upvotes: 0
Views: 59
Reputation: 7770
forEach takes a callback function and you are not waiting for the loop to finish. try something like this
const express = require("express");
const app = express();
const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
const mongourl = "mongodb://localhost:27017/test";
let str = "";
MongoClient.connect(mongourl, async function (err, client) {
assert.equal(null, err);
const db = client.db("test");
const cursor = db.collection("projects.testproject.exampleChannel.germany.parameter").find();
while (await cursor.hasNext()) {
const item = await cursor.next();
if (item != null) {
str += JSON.stringify(item);
console.log(`1 ${str}`);
}
}
client.close();
console.log(`2 ${str}`);
});
Upvotes: 1