Does mongoose allow for multiple database requests concurrently?

前端 未结 1 1390
南笙
南笙 2020-12-24 07:21

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

相关标签:
1条回答
  • 2020-12-24 08:03

    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.

    0 讨论(0)
提交回复
热议问题