Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS query MongoDB returning null

I'am new to Node.js and MongoDB and I am trying it out.

I made a collection called footIco. When I query MongoDB in the console with db.footIco.find(), it return all the data.

However when I query MongoDB from Node.js it doesn't return any data.

I can see the connection in MongoDB server console.

Here is my Node.js script;

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/footIco';

var findIco = function(db, callback) {
   var cursor =db.collection('footIco').find();
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
           console.dir(doc);
      }
   });
};

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  findIco(db, function() {
      db.close();
  });
});

Can anyone tell me what is wrong with this. It's pretty much a copy and paste from the MongoDB tutorial

like image 959
MadeInDreams Avatar asked Sep 18 '26 04:09

MadeInDreams


1 Answers

This line:

assert.equal(err, null);

it is a JavaScript specific, that handlers that throws error will throw nowhere, I would recommend changing it to console.log(err) or just modify your callback to handle err parameter.

like image 200
Dawid Pura Avatar answered Sep 20 '26 19:09

Dawid Pura