0

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}}}

3
  • 1
    This is because of the event loop. You will need to have a look at event loop, how callStack works. hackernoon.com/understanding-js-the-event-loop-959beae3ac40. have a look at this and try to understand callstack. Commented Mar 11, 2020 at 9:19
  • youtube.com/watch?v=v0QTqHXiVNw this video from Dev Ed explains it in very easy way. Please have a look at this. Commented Mar 11, 2020 at 9:21
  • 2
    Inshort: .find() is an async operation and subsequently .forEach takes a callback function to get you results. The execution is not going to wait for that loop to finish off before reaching console.log("2 "+str) Commented Mar 11, 2020 at 9:38

1 Answer 1

1

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}`);
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.