【发布时间】:2018-01-02 13:16:29
【问题描述】:
我正在将 mongodb 与 mongoose 一起使用。
我有一些与下一个模型的集合:
一个。型号:产品
b.型号:详情
我需要返回一个包含 Product 中总项目的数据集,并且对于每个产品项目,我需要通过在 Model Details 中循环您的详细信息来计算数量。
我的问题是如何在我的数据数组中设置数量,在执行“promise_3”之后。 我需要知道数据数组的索引才能做到这一点,但我该怎么做呢?
结果会是这样的:
response:{
total:1012,
data:[
{id:'1',name:'xx', quantity:10},
{id:'2',name:'yy', quantity:110},
{id:'3',name:'zz', quantity:130},
...
]}
//我的承诺代码
var response={};
var promise_1=Product.count({}).lean().exec();
var prommise_2=function (data){
return Product.find(conditions)
.limit(pageSize)
.skip(pageSize*(pageNumber-1))
.sort(oorder)
.lean()
.exec();
}
var prommise_3= function (item){
return Details.aggregate(
[
{ "$match": {
cod_material: item._id
}},
{$lookup:
{
from: "estoqueMov", //use the name of database collection not mongoose model
localField: "cod_mov",
foreignField: "_id",
as: "mov_doc"
}
},
{ $unwind: "$mov_doc" },
{$lookup:
{
from: "Details", //use the name of database collection not mongoose model
localField: "mov_doc.cod_tipo_mov",
foreignField: "_id",
as: "tipo_mov_doc"
}
},
{ $unwind: "$tipo_mov_doc"},
{ "$group": {
_id: "$cod_material",
total: { "$sum":
{"$multiply":
["$quantidade",{"$cond":[
{"$eq":["$tipo_mov_doc.tipo","Entrada"]} , 1,-1]}]
}
}
}}
]);
}
//promise_1 is done
promise_1.then( function(count){
response.total=count;
return promise_2()
})
.then( function (data){
response.data=data;
for (var i = 0; i < response.data.length; i++) {
var item=response.data[i];
//??item.quantity=0;
return promise_3(item)
}
})
.then( function (results){
var total=results.length>0?results[0].total:0;
//Here is my problem How could I set the response.data index array??
response.data[??????].quantity=total;
callback(null,response,res);
});
【问题讨论】:
-
在第二个回调中,你在
for循环的中间return。我不认为那是你想要的。 -
@Bergi,我需要使用 promise_3 计算每个产品项目的数量。我的意图是创建一个循环并调用 promise_3。你能提出一些不同的建议吗?
-
好吧,要么生成一个
promise_3承诺数组,使用Promise.all,然后以几乎相同的方式迭代results(保留顺序,因此您可以轻松地使用索引到数据数组中)。或者你将那些.then()调用放在循环中,这样每个promise_3都有自己的回调(然后可以通过闭包provided that the loop scope is correct 使用索引)。无论如何,放下或移动那个return。
标签: node.js mongodb mongoose promise