2017-05-18 160 views
0

如何将来自聚合函数的查询结果存储到变量中并在其他函数中使用它。 我有这个功能计数记录:Mongoose存储查询结果变量

const utilitiesFunctions = {}; 
utilitiesFunctions.conteoBatch = (callback) => { 
    workOrder.aggregate({ 
    $unwind: "$batches" 
    }, { 
    $group: { 
     _id: "$batches", 
     total: { 
     $sum: 1 
     } 
    } 
    }, function(err, conteos) { 
    callback(conteos); 
    }); 
} 

module.exports = utilitiesFunctions; 

的resutl是:

[ { _id: 591c9fc757ddf611fc7c5840, total: 2 }, 
    { _id: 591c9a9e5683f81b8c48e44c, total: 1 } ] 

我使用一个循环来搜索与下位计数的_id。如何能通过ID中的变量其他验证功能,使用它,像这样:

var idb = utilitiesFunctions.conteoBatch();//idb=591c9fc757ddf611fc7c5840 

回答

0

如果我理解正确的话,你需要什么,必须是这样的

let objWithSmallestCount = {}; 
let results = utilitiesFunctions.conteoBatch(); 

让我们说你的算法中寻找最小数为isSmallestCount()

for (let result of results) { 
    if (isSmallestCount(result.total) { 
     objWithSmallestCount = result; 
    } 
} 

从这点上你可以做任何你想做的事情

let id = objWithSmallestCount._id; 
+0

这是行不通的。 – joselegit

+0

你得到的输出/错误是什么? – marto

+0

该变量是空的 – joselegit