繁体   English   中英

如何使用 mongoose 从 mongodb 中的多个 collections 获取数据?

[英]How to get data from multiple collections in mongodb using mongoose?

我在 mongoDB 中有 3 个 collections 具有以下结构

用户:

"name":""
"email":""
"phone":""
"city":""
"customerID":""

船舶:

"address":""
"city":""
"pincode":""
"porderID":""
"customerID":""

订单:

"productName":""
"quantity":""
"pricing":""
"mrp":""
"porderID":""
"customerID":""

我如何编写一个 get 请求或聚合 function 来返回 json 中的所有 customerID 像这样?

[{

customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],

customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],

}]

任何的意见都将会有帮助。

不太清楚你想要什么......没有输入/输出示例,没有有效的 JSON...... 并不容易,但我认为你正在寻找这样的东西:

该查询是一个嵌套的$lookup ,其中每个用户使用customerID将订单与orders连接起来,并且订单也使用customerIDships连接。

db.users.aggregate([
  {
    "$lookup": {
      "from": "orders",
      "localField": "customerID",
      "foreignField": "customerID",
      "as": "BuyOrder",
      "pipeline": [
        {
          "$lookup": {
            "from": "ships",
            "localField": "customerID",
            "foreignField": "customerID",
            "as": "ShipmentDetail"
          }
        }
      ]
    }
  },
  
])

这里的例子

您还可以将$project阶段添加到 output 仅您想要的字段,例如结果为:

[
  {
    "BuyOrder": [
      {
        "ShipmentDetail": [
          {
            "address": "",
            "city": "",
            "pincode": ""
          }
        ],
        "porderID": "",
        "pricing": "",
        "productName": "",
        "quantity": ""
      }
    ],
    "customerID": ""
  }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM