gpt4 book ai didi

node.js - 查询时 mongodb native 驱动程序错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:13 26 4
gpt4 key购买 nike

我正在使用 mongodb native 驱动程序编写过滤器,但当您运行查询时,它会导致我出现此错误。

就这个驱动程序而言,它没有 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

最佳答案

最好使用async在这种情况下使用库,因为它简化了代码。如果您需要运行多个相互依赖的任务,并且当它们全部完成后执行其他操作,请使用<强> 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);
});
};

关于node.js - 查询时 mongodb native 驱动程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35490871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com