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?
Mongoose provides built-in and custom validators, and synchronous and asynchronous validators.
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.
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.
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.
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.
var mongojs = require('mongojs'); var db = mongojs('localhost/test'); var mycollection = db.collection('mycollection');
var mongo = require('mongoskin'); var db = mongo.db("mongodb://localhost:27017/test", {native_parser:true});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With