Node.js 使用async node js运行大量mongodb查询
我有一个在req.body中获取以下部分的服务:Node.js 使用async node js运行大量mongodb查询,node.js,mongodb,async.js,Node.js,Mongodb,Async.js,我有一个在req.body中获取以下部分的服务: dataType: null, fechaI: null, fechaF: null, checkedList: [] 我必须运行与选中列表长度相等的查询数,并向客户端返回单个响应。 我有另一个名为queries.js的文件,它导出了我使用的所有查询,所以假设我想要获取所有文档并获取它们的总和,我只需要这样做 const queries = require('./queries.js') // example in the co
dataType: null,
fechaI: null,
fechaF: null,
checkedList: []
我必须运行与选中列表长度相等的查询数,并向客户端返回单个响应。
我有另一个名为queries.js的文件,它导出了我使用的所有查询,所以假设我想要获取所有文档并获取它们的总和,我只需要这样做
const queries = require('./queries.js')
// example in the controller
exports.example = function(req,resp){
query.ej(req,resp)
}
我想要实现的是:
1.迭代检查列表中的所有项并执行查询
2.返回包含所有查询结果的单个数组
我尝试过使用async.paralel,但是req的属性没有传递到查询函数,我认为该函数不会返回所有结果
async.parallel([
function(cb){
for( var i=0;i<req.body.checkedList.length;i++){
//res is used to store the temporary variables to be passed on to the query
var res ={ }
res.context= {
sujeto :"TOS060602S77",
type : req.body.dataType,
fechaInicio : req.body.fechaI,
fechaFin : req.body.fechaF,
moneda : req.body.checkedList[i].moneda
}
query[req.body.checkedList[i].action](req,res,resp,cb)
}
}
], function(err,results){
console.log(results)
})
本质上,我得到的错误是,传递给查询的对象在执行时未定义,可能是async.parallel方法的结构,因为我认为它不会在一个响应中返回所有结果。查询对象在哪里?查询对象是从另一个js文件导入的,其中我有一个mongodb查询,就像上一个代码示例中的一样,只需打印qyery对象即可
exports.action= function(req,resp,res, callback){
MongoClient.connect(url,function(err,client){
if (err) console.log(err)
let dbo = client.db("SomeDB")
var collection ="Somecollection"
console.log(res.context)
dbo.collection(collection).aggregate([
//do something
]).toArray(function(err,data){
if (err) callback(err)
if (!data) console.log(" no data")
if (data) {
var results= {datos : data}
callback(data)
console.log(results)
}
})
})
}