Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to connect to mongodb synchronously in nodejs

I want to make use of the promises feature where in I can connect to mongodb synchronously and I can reuse the connection by passing it on to different modules.

Here is something that I came up with

class MongoDB {

    constructor(db,collection) {      
      this.collection = db.collection(collection);
    }

    find(query, projection) {
        if(projection)
            return this.collection.find(query, projection);
        else
            return this.collection.find(query);
    }
}

class Crew extends MongoDB {

    constructor(db) {        
        super(db,'crews');
    }

    validate() {

    }
}

I want to setup a connection somewhere in my initial code like the one below and then reuse the connection for different classes, just like how mongoose or monk does but using only the node-mongodb-native package.

MongoClient.connect(url)
          .then( (err,dbase) => {
                global.DB = dbase;
              });


var Crew = new CrewModel(global.DB);


Crew.find({})
   .then(function(resp) {
      console.log(resp);
   });

Right now, the db returns undefined inside the main MongoDB class and am not able to debug this one out through google or the documentation.

Edit: I had assumed that a promise was synchronous but that is not the case.

like image 718
Bazinga777 Avatar asked May 10 '16 19:05

Bazinga777


People also ask

How would you connect a MongoDB database to node js?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });

Is Mongoose connect synchronous?

Mongoose provides built-in and custom validators, and synchronous and asynchronous validators.

Is MongoDB synchronous?

MongoDB uses two forms of data synchronization: initial sync to populate new members with the full data set, and replication to apply ongoing changes to the entire data set.


1 Answers

To reuse the connection I would create a module like this.

module.exports = {

    connect: function(dbName,  callback ) {
       MongoClient.connect(dbName, function(err, db) {

       _db = db;
       return callback( err );
    });
},

     getDb: function() {
        return _db;
     }
};

After that you can connect to the database before starting your application

MongoConnection.connect("mongodb://localhost:27017/myDatabase", function(err){
    app.listen(3000, function () {
        // you code
    });
});

Considering you created the module in a js file you can simply use require to get the databaseConnection

var dbConnection = require("./myMongoConnection.js");

and to get the connection use

var db = MongoConnection.getDb();
like image 50
V. Lovato Avatar answered Oct 17 '22 02:10

V. Lovato