mongodb本机驱动程序错误的查询

我正在使用mongodb本机驱动程序编写filter,但是当您运行查询时,这会导致此错误。

在这个驱动程序的情况下,它没有exec?

什么是执行此查询的另一种方法?

exports.findAll = function(req, res) { MongoClient.connect(url, function(err, db) { var section = req.params.section; var collection = db.collection(section); var filter = req.query.filter ? {nameToLower: new RegExp('^' + req.query.filter.toLowerCase())} : {}; var query = collection.find(filter); var count = 0; collection.count(filter, function (error, result) { count = result; }); if(req.query.order) { query.sort(req.query.order); } if(req.query.limit) { query.limit(req.query.limit); if(req.query.page) { query.skip(req.query.limit * --req.query.page); } } query.exec(function (error, results) { res.json({ count: count, data: results }); }); }); }; 

错误:

 TypeError: undefined is not a function 

在这种情况下最好使用asynchronous库,因为它简化了代码。 在需要运行多个相互依赖的任务的情况下,以及在完成其他任务时,使用async.series()模块。 以下演示如何在你的情况下做到这一点:

 exports.findAll = function(req, res) { var locals = {}, section = req.params.section, filter = !!req.query.filter ? {nameToLower: new RegExp('^' + req.query.filter.toLowerCase())} : {}; async.series([ // Connect to DB function(callback) { MongoClient.connect(url, function(err, db) { if (err) return callback(err); locals.collection = db.collection(section); //Set the collection here, so the next task can access it callback(); }); }, // Get count function(callback) { locals.collection.count(filter, function (err, result){ if (err) return callback(err); locals.count = result; //Set the count here callback(); }); }, // Query collection function(callback) { var cursor = locals.collection.find(filter); if(req.query.order) { cursor = cursor.sort(req.query.order); } if(req.query.limit) { cursor = cursor.limit(req.query.limit); if(req.query.page) { cursor = cursor.skip(req.query.limit * --req.query.page); } } cursor.toArray(function(err, docs) { if (err) return callback(err); locals.docs = docs; callback(); }); } ], function(err) { //This function gets called after the three tasks have called their "task callbacks" if (err) return next(err); // Here locals will be populated with 'count' and 'docs' res.json({ count: locals.count, data: locals.docs }); res.render('user-profile', locals); }); };