与Mongoose相比,MongoDB本地Node.js驱动程序性能糟糕,我做错了什么?

我有一个简单的node/express应用程序,需要获取存储在示例MongoDB集合(32-bit, localhost, Windows)的2个文档。 我可以使用native driverMongoose ORM

与本地驱动程序去拆除我的应用程序。 有一个ApacheBench(3300请求,一次5),整个事情超时…

 Completed 330 requests apr_pollset_poll: The timeout specified has expired (70007) 

通过Mongoose访问MongoDB的同一个集合只是通过比较来完成任务

 ... Completed 2970 requests Completed 3300 requests Finished 3300 requests ... Requests per second: 244.49 [#/sec] (mean) Time per request: 61.353 [ms] (mean) 

这是一个巨大的差异,显然我使用本机驱动程序时做了一些非常错误的事情。 以下是这两种方法的代码以及存储在数据库中的数据。

只有两个文件存储在数据库中:

 { "_id": "51bmdft4a487e771411ce8ef", "name": "Gintoki", "email": "sakata@yorozuya.com", "friends": [ "Shinpachi", "Kagura", "Tsukuyo" ] }, { "_id": "51388p50bed4dghy4308745d", "name": "Elizabeth", "email": "eli@ossan.io", "friends": [ "Katsura" ] } 

使用本机MongoDB驱动程序:

 var app = require( 'express' )(), MongoClient = require( 'mongodb' ).MongoClient, DB_URL = 'mongodb://localhost:27017/testDB'; app.get( '/mongotest', function ( req, res ) { MongoClient.connect( DB_URL, function ( err, db ) { if( !err ) { var collection = db.collection( 'People' ); collection.find().toArray(function(err, items) { res.send( JSON.stringify( items ) ); }) } }) }) app.listen( 5000 ); 

输出 :超时一分钟只完成ab 3300个请求中的330个


使用Mongoose:

 var app = require( 'express' )(), mongoose = require( 'mongoose' ), DB_URL = 'mongodb://localhost:27017/testDB'; app.get( '/mongotest', function ( req, res ) { mongoose.connect( DB_URL ); var PeopleSchema = mongoose.Schema({ name: String, email: String, friends: Array }), People = mongoose.model( 'People', PeopleSchema ), db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { People.find({}, function ( err, item ) { res.send( item ); }) }) }) app.listen( 5000 ); 

输出 :与本地驱动程序相比,速度更快。 ab在几秒钟内完成。

任何人都可以帮我弄清楚我的原生驱动程序有什么问题?

很确定的问题是,在本地版本中,每个请求都会打开一个新的连接池。 重做你的代码,以便MongoClient.connectMongoClient.connect调用在启动过程中只进行一次