Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does mongoose allow for multiple database requests concurrently?

Tags:

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.

like image 483
alexk Avatar asked Apr 06 '12 04:04

alexk


People also ask

Can Mongoose connect to multiple databases?

Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection.

Can Mongoose queries be chained?

Mongoose lets you structure queries using chaining or, equivalently, using POJOs in a single function call. Model.

Can I use MongoDB and Mongoose at the same time?

Connecting to MongoDBMongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose. connect() , as shown below. You can get the default Connection object with mongoose.


1 Answers

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.

like image 172
Eve Freeman Avatar answered Oct 24 '22 12:10

Eve Freeman