0

I am new in nodejs and currently working on node.js and mongodb.This my mongodb connection code

var mongodb = require("mongodb");

var MongoClient = mongodb.MongoClient;

var url = 'mongodb://localhost:27017/mydb';

var mongodbStore = {};

var db;

MongoClient.connect(url, function (err, dataBase) {
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {

        debug("Connected to mongodb. Initialising saved listeners...");
        db = dataBase;
        var manager = require('./managers/manager');
    }
});

mongodbStore.add = function(name, data) {
    var collection = db.collection('listeners');

    if (collection) {
        collection.insert("listener", JSON.stringify(data));
    }
};

I will call "add" function from my another file.But now I am getting Error on first line in add function

var collection = db.collection('listeners');

Error is:

TypeError: Cannot read property 'collection' of undefined
    at Object.mongodbStore.add (C:\Node.js Listeners 2\mongodbStore.js:54:21)
    at C:\Node.js Listeners 2\managers\manager.js:46:18
    at Server.<anonymous> (C:\Node.js Listeners 2\managers\tcpManager.js:54:10)
    at Server.emit (events.js:104:17)
    at net.js:1171:12
    at process._tickCallback (node.js:355:11)

Can any one please tell me,What is wrong here and what is correct way?

Abhay Kulkarni
  • 73
  • 1
  • 3
  • 5
  • 2
    You are apparently calling `.add()` before the connect has completed and filled in the `db` variable. It's often a bad sign when you're setting a higher scoped variable from an async callback like you are doing with the `db` variable because the rest of your code has no idea when that variable is actually valid. You probably need to trigger the action that is causing this issue from the `.connect()` callback. – jfriend00 Jan 12 '16 at 07:19
  • Thank you for your reply,Can you please share with me callback example of mongodb connect.Or can you modify my code as you said? – Abhay Kulkarni Jan 12 '16 at 07:38
  • 1
    You need to understand the concept of returning variables from a callback, please refer to this question for a better understanding [**How do I return the response from an asynchronous call?**](http://stackoverflow.com/questions/14220321/) – chridam Jan 12 '16 at 09:32
  • Thank you Chridam for your ans...I will check this – Abhay Kulkarni Jan 12 '16 at 10:55

1 Answers1

0

This is because db would be undefined since you are assigning its value from a callback. You need to move your code into the callback passed to connect like so.

var mongodb = require("mongodb");

var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/mydb';
var mongodbStore = {};

MongoClient.connect(url, function (err, db) {
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {

        debug("Connected to mongodb. Initialising saved listeners...");
        var manager = require('./managers/manager');

        mongodbStore.add = function(name, data) {
           var collection = db.collection('listeners');

           if (collection) {
              collection.insert("listener", JSON.stringify(data));
           }
        };
    }
});
codejockie
  • 9,020
  • 4
  • 40
  • 46