0

I am new to node programming, and I have got the following question:

why do "database connected" and "handleDataResult" not log correctly in the node console when I launch my script using node index.js command?

My code logs only "no callback" and exits immediately.

const mongojs = require('mongojs');
var url = "mongodb://<username>:<password>@ds237748.mlab.com:37748/anbieter";
var db = mongojs(url);
var mycollection = db.collection('Anbieter');

db.on('connect', function () {
    console.log('database connected')
});

db.mycollection.find({}, handleDataResult);

var handleDataResult = function (err, docs){
  console.log("handleDataResult");
}

console.log("no callback");
Vickel
  • 7,879
  • 6
  • 35
  • 56
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – lleon Feb 15 '18 at 22:27

1 Answers1

0

Node.js is asynchronous. Put your code inside your db connection function.

const mongojs = require('mongojs');
var url = "mongodb://<username>:<password>@ds237748.mlab.com:37748/anbieter";
var db = mongojs(url);
var mycollection = db.collection('Anbieter');
db.on('connect', function () {
    console.log('database connected')
    db.mycollection.find({}, handleDataResult);
});

var handleDataResult = function (err, docs){
    console.log("handleDataResult");
}

console.log("no callback");
Wesgur
  • 3,140
  • 3
  • 18
  • 28