【问题标题】:Mongo DB get the children informationMongodb获取孩子信息
【发布时间】:2018-10-26 09:56:14
【问题描述】:

以下是我在运行以下查询时得到的响应

Order.find().then((find) => {
        res.json(find);
    });

[  
   {  
      "isPrime":false,
      "orderStatus":"Pending",
      "orderTotal":"27.98",
      "orderType":"x",
      "subOrderId":"x",
      "children":[  
         "5bd105dc1b85bc2faca27603",
         "5bd105dd1b85bc2faca2760b",
         "5bd105dd1b85bc2faca27613"
      ],
      "_id":"x",
      "deliveryDate":"x",
      "orderChannel":"xx",
      "orderDate":"xZ",
      "orderLabel":"NA",
      "shipDate":"x",
      "__v":0
   },

]

如何在同一查询中或可能在不同查询中获取有关孩子的信息?

【问题讨论】:

  • 你想只取回 children 字段吗?
  • 否,子数据作为一个整体,即一个子数据是表中的客户信息。需要获取子数据(id、客户名称、地址...)
  • 你必须在聚合管道中使用 $lookup。像Order.aggregate({$lookup:{from:replace with child collection name, localField:"children", foreignField:"_id", as:"chidren"}}) 这样的东西。确保 locaField 和 foreignField 类型匹配。
  • 得到错误 MongooseError: Mongoose 5.x 不允许将一系列运算符传递给Model.aggregate()。而不是Model.aggregate({ $match }, { $skip }),而是Model.aggregate([{ $match }, { $skip }])

标签: node.js reactjs mongodb


【解决方案1】:

让它与以下代码一起工作 孩子 1 到 3 是子文档。也必须更改我的架构

来自

children:[{type:Schema.ObjectId, ref:"ONLINE_ORDER_ITEMS"} , {type:Schema.ObjectId, ref:"ONLINE_ORDER_CUSTOMERS"}, {type:Schema.ObjectId, ref:"ONLINE_ORDER_SHIPMENTS"}]

 children1:[{type:Schema.ObjectId, ref:"ONLINE_ORDER_ITEMS"}],
    children2:[{type:Schema.ObjectId, ref:"ONLINE_ORDER_CUSTOMERS"}],
    children3:[{type:Schema.ObjectId, ref:"ONLINE_ORDER_SHIPMENTS"}]



 Order.find({ 'orderStatus': typeFlag}).populate('children1').populate('children2').populate('children3').then((find) => {
        res.json(find);
    });

【讨论】:

    猜你喜欢
    • 2014-11-18
    • 2015-09-06
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2021-03-12
    • 1970-01-01
    相关资源
    最近更新 更多