-1

Im making a server and need some way to be identified if mongojs connected successfully to the mongodb database when i call the function :

    mongojs.connect(connectionString, collections);

Is there a callback or an event listener i could use?

Mladen Kajic
  • 125
  • 1
  • 2
  • 7

1 Answers1

1

As you can read in MongoJS docs (https://github.com/mafintosh/mongojs#events), there is one event which you can listen to know when the db is ready:

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

You need to make a variable assignment of the sentence you posted, as I show you below:

var db = mongojs.connect(connectionString, collections);

and then use the ready event to listen the db connection

jesusbotella
  • 626
  • 4
  • 8
  • I see :) thank you. But is there an event to tell me it failed? – Mladen Kajic Jun 08 '15 at 22:22
  • I see there is an "error" event but as I've tried, it doesn't get called if a connection to the database failed – Mladen Kajic Jun 08 '15 at 22:26
  • I didn't tried it, but I suggest you to use the official [MongoDB Driver](http://mongodb.github.io/node-mongodb-native/) or [mongoose](http://mongoosejs.com/) instead MongoJS. Those frameworks give you a lot of more options than MongoJS. – jesusbotella Jun 08 '15 at 22:41
  • Right i will definitely give those a look :) thanks for your help! – Mladen Kajic Jun 08 '15 at 22:43
  • 1
    mongojs does not open a connection until the first request is made. You need to use db.open() to force it to connect before any requests. – Joe Jun 17 '15 at 14:29