Does mongoose allow for multiple database requests concurrently?

Problem

I read that Mongoose will only open one connection at maximum per collection, and there's no option to change this.

Does this mean that a slow mongo query will make all subsequent queries wait?

I know everything in node.js is non-blocking, but I'm wondering whether a slow query will delay the execution of all subsequent queries. And whether there is a way to change this.

Problem courtesy of: alexk

Solution

It does only use one connection, if you use the default method where you do mongoose.connect(). To get around this, you can create multiple connections, and then tie a model pointing to the same schema to that connection.

Like so:

var conn = mongoose.createConnection('mongodb://localhost/test');
var conn2 = mongoose.createConnection('mongodb://localhost/test');
var model1 = conn.model('Model', Schema);
var model2 = conn2.model('Model', Schema);
model1.find({long query}, function() {
   console.log("this will print out last");
});
model2.find({short query}, function() {
   console.log("this will print out first");
});

Hope that helps.

Update Hey, that does work. Updating from the comments, you can create a connection pool using createConnection. It lets you do multiple queries from the same model concurrently:

var conn = mongoose.createConnection('mongodb://localhost/test', {server:{poolSize:2}});
var model = conn.model('Model', Schema);
model.find({long query}, function() {
   console.log("this will print out last");
});
model.find({short query}, function() {
   console.log("this will print out first");
});

Update 2 -- Dec 2012
This answer may be slightly outdated now--I noticed I've been continuing to get upvotes, so I thought I would update it. The mongodb-native driver that mongoose wraps now has a default connection pool size of 5, so you probably don't need to explicitly specify it in mongoose.

Solution courtesy of: Eve Freeman

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.