1

Normally you would do something like:

var db = new mongo
    .Db('test', new mongo.Server('127.0.0.1', 27017), {w: 1})
    .open(function (error, database) {

        if (error) throw error

        console.log('Connected to database test')
    })

I, however, want to connect to mongodb synchronously. So I'd need a method I can use in this way:

var db = new mongo.openDb('test', new mongo.Server('127.0.0.1', 27017), {w: 1})

console.log('Connected to database test')

Is there anything like this?

2
  • Why do you want to do this? It's best to embrace the asynchronicity with Node.js rather than fight it. Commented Jul 20, 2014 at 0:06
  • @ JohnnyHK The advantage of asynchronicity is that the code does not block and also that it's possible to handle errors properly. If your app depends on the database for further execution and is supposed to crash and throw an error anyway, you can as well skip the whole callback/asynchronous hassle… Commented Jul 20, 2014 at 0:13

2 Answers 2

1

You might want to checkout mongoskin, it connects the database without callback. Here is the example from its github:

var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/integration_tests", {native_parser:true});
db.bind('article');
db.article.find().toArray(function(err, items) {
    db.close();
});
Sign up to request clarification or add additional context in comments.

Comments

0

If you use something like node-fibers, then you could do something like what you outlined above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.