Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect synchronously to mongodb

I would like to connect to mongodb first, then run everything else in my application.

To do it I have to write something like:

MongoClient.connect("mongodb://localhost/test", function(err, connection) {     if (err) { console.error(err); }     db = connection;      var app = express();      // Include API V1     require("./apiv1.js")(app, db);      app.listen(3000, function(err) {         if (err) { console.error(err); } else { console.log("Started on *:3000"); }     }); }); 

This makes my app to be completely indented inside the .connect function... Which looks ugly and takes space while I work on my project.

I think the best solution would be have the MongoDB connection synchronous (even because witout the DB connection my app cannot work so why should I do something while it's connecting?) and then run the rest of my code.

How can I do?

like image 586
Fez Vrasta Avatar asked Sep 18 '14 09:09

Fez Vrasta


People also ask

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.

How does MongoDB connect to MongoClient?

Connect to a Replica Setconst MongoClient = require('mongodb'). MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017,localhost:27018/?replicaSet=foo'; // Database Name const dbName = 'myproject'; // Use connect method to connect to the Server MongoClient.

What is MongoClient in Java?

public class MongoClient extends Mongo implements Closeable. A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.


1 Answers

You can't connect to MongoDB synchronously, but you may get rid of this ugly callback from your code.

The best way to do it is to adopt some wrapper around node-mongodb-native driver.

Take a look at the following modules.


mongojs

var mongojs = require('mongojs'); var db = mongojs('localhost/test'); var mycollection = db.collection('mycollection'); 

mongoskin

var mongo = require('mongoskin'); var db = mongo.db("mongodb://localhost:27017/test", {native_parser:true}); 

monk

var monk = require('monk'); var db = monk('localhost/test'); var users = db.get('users') 

Of course, internally all of them are establishing MongoDB connection asynchronously.

like image 102
Leonid Beschastny Avatar answered Oct 17 '22 17:10

Leonid Beschastny