How to connect to mongodb synchronously in nodejs

I want to use the promises function, where I can connect to mongodb synchronously, and I can reuse this connection by passing it to other modules.

Here is what 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 establish a connection somewhere in my source code, as shown below, and then reuse the connection for different classes, just like a mongoose or monk does, but only uses its own node-mongodb package.

 MongoClient.connect(url) .then( (err,dbase) => { global.DB = dbase; }); var Crew = new CrewModel(global.DB); Crew.find({}) .then(function(resp) { console.log(resp); }); 

At the moment, db is returning undefined inside the main MongoDB class, and I cannot debug it through Google or the documentation.

Edit: I assumed that the promise was synchronous, but it is not.

+6
source share
3 answers

To reuse the connection, I would create such a module.

 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 launching the application

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

Given that you created the module in the js file, you can simply use require to get connectionConnection

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

and to use the connection

 var db = MongoConnection.getDb(); 
+6
source

Another option using ES6 classes creates a singleton object that you can access again. It inspired @ user3134009 to answer here .

 const EventEmitter = require('events'); const MongoClient = require('mongodb').MongoClient; const config = require('config'); let _db = null; class MongoDBConnection extends EventEmitter { constructor() { super(); this.emit("dbinit", this); if (_db == null) { console.log("Connecting to MongoDB..."); MongoClient.connect(config.dbs.mongo.url, config.dbs.mongo.options, (err, db) => { if (err) { console.error("MongoDB Connection Error", err); _db = null; } else { console.log("Connected to MongoDB", config.dbs.mongo.url); db.on('close', () => { console.log("MongoDB closed", arguments); _db = null; }); db.on('reconnect', () => { console.log("MongoDB reconnected", arguments); _db = db; }); db.on('timeout', () => { console.log("MongoDB timeout", arguments); }); _db = db; this.emit('dbconnect', _db); } }); } } getDB() { return _db; } } module.exports = new MongoDBConnection(); 
0
source

I struggled with this problem for a while and, in particular, configured and saved the MongoDb connection in AWS lambda functions through calls. Thanks to @toszter's answer, I finally came up with the following solution:

 const mongodb = require('mongodb'); const config = require('./config.json')[env]; const client = mongodb.MongoClient; const mongodbUri = `mongodb://${config.mongo.user}:${config.mongo.password}@${config.mongo.url}/${config.mongo.database}`; const options = { poolSize: 100, connectTimeoutMS: 120000, socketTimeoutMS: 1440000 }; // connection object let _db = null; class MongoDBConnection { constructor() {} // return a promise to the existing connection or the connection function getDB() { return (_db ? Promise.resolve(_db) : mConnect()); } } module.exports = new MongoDBConnection(); // transforms into a promise Mongo client.connect function mConnect() { return new Promise((resolve, reject) => { console.log('Connecting to Mongo...'); client.connect(mongodbUri, options, (error, db) => { if (error) { _db = null; return reject(error); } else { console.log('Connected to Mongo...'); _db = db; resolve(db); } }); }); } 

To use it in a controller or app.js:

  const mongoConfig = require('mongoConfig'); mongoConfig.getDB() .then(db => db.collection('collection').find({})) .catch(error => {...}); 
0
source

All Articles