its*_* me 7 javascript mongodb node.js
我有横切和购买集合,这是现在我想要将横断面和购买细节转换成单个集合.基于transectionid我们需要结合文件
下面是我的横断面集合数据
{
"transectionid": "1",
"transectionamount": "2000",
"transectiondate": "2016-07-12 19:22:28",
},
{
"transectionid": "2",
"transectionamount": "1000",
"transectiondate": "2016-07-12 20:17:11",
}
Run Code Online (Sandbox Code Playgroud)
下面是我的购买集合数据
{
"purchaseid": "1",
"transectionid": "1",
"itemprice": "1200",
"itemcode": "edcvb",
"itemquantity": "1",
},
{
"purchaseid": "2",
"transectionid": "1",
"itemprice": "800",
"itemcode": "dfgh",
"itemquantity": "2",
},
{
"purchaseid": "3",
"transectionid": "2",
"itemprice": "1000",
"itemcode": "zxcvb",
"itemquantity": "1",
}
Run Code Online (Sandbox Code Playgroud)
我的期望结果:这是订单集合应该如何存储{
"transectionid" : "1",
"transectionamount": "2000",
"transectiondate": "2016-07-12 19:22:28",
"items" : [
{
"purchaseid": "1",
"itemprice":"1200",
"itemcode": "edcvb",
"itemquantity": "1",
},
{
"purchaseid": "2",
"itemprice": "800",
"itemcode": "dfgh",
"itemquantity": "2",
}
]
}
{
"transectionid" : "2",
"transectionamount": "1000",
"transectiondate": "2016-07-12 20:17:11",
"items" : [
{
"purchaseid": "3",
"itemprice":"1000",
"itemcode": "zxcvb",
"itemquantity": "1",
}
]
}
Run Code Online (Sandbox Code Playgroud)
根据您的预期结果,您可能希望获取所有将填充的购买数据作为项目的交易。
在您的结构中transectionid
是类型,您可能不会在您的模式中String
使用。ref
所以 populatetransectionid
你应该使用,$lookup
因为我们可以定义from
,localField
和foreignField
。为此,您不需要ref
在架构中使用它。
并且您应该添加items: []
您的Transaction
架构,因为如果您不添加,您可能不会得到items
结果。
在transaction
控制器中可以添加此功能来获取所有以数据为项目的交易purchase
。
对于from
字段,$lookup
您应该使用小写和复数形式的集合名称,因为当 mongoose 创建集合时,它会变成复数。就像您导出的架构名称一样PurchasesData
,它将创建类似purchasesdatas
喜欢:
exports.getTransactions = function(req,res){
Transection.aggregate([
{$lookup:{from:"purchases", localField:"transectionid", foreignField:"transectionid", as:"items"}}
]).exec(function(err, result) {
if(err) {
console.log('error============', err);
return res.status(400).send("error occurred");
}else{
console.log(result);
return res.status(200).send(result);
}
});
};
Run Code Online (Sandbox Code Playgroud)