我指的是一个集合中的一个领域到另一个领域。但是每当有重复项时,返回的数组都是不同的

时间:2018-09-23 14:43:25

标签: node.js mongodb aggregation-framework

router.get('/orderSelect', (req, res, next) =>{
    orderSchema.aggregate([   
        { $lookup:
            {
                from: 'productschemas',
                localField: 'orderItem.productId',
                foreignField: '_id',
                as: 'product'
            }
        }
    ], (err, orderSchema) =>{
        if(err) res.json(err);
        else res.json(orderSchema);
    });
});

产品方案:

[
  {
    "_id": "5ba26ff33318b51e20a80fb3",
    "productExist": true,
    "productName": "Oppo",
    "supplierId": "5b9f1e2f5929760568283f95",
    "brandId": "5b9d19e8316e8d2660f26394",
    "categoryId": "5b9d20de9c21fd1b78410d52",
    "productPrice": 4300,
    "productQuantity": 320,
    "productMax": 10,
    "productMin": 4,
    "productTimeStamp": "2018-09-19T15:49:07.177Z",
    "__v": 0
  }
]

orderSchema

[
  {
    "_id": "5ba79a638cef34091c143def",
    "orderItem": [
      {
        "_id": "5ba7a37b4c40dc24d8f4f403",
        "productId": "5ba26ff33318b51e20a80fb3",
        "productPrice": 4300,
        "productQuantity": 2,
        "productTotal": 8600
      },
      {
        "_id": "5ba7a37b4c40dc24d8f4f402",
        "productId": "5ba34f0c133e492a04731c49",
        "productPrice": 2000,
        "productQuantity": 1,
        "productTotal": 2000
      },
      {
        "_id": "5ba7a37b4c40dc24d8f4f401",
        "productId": "5ba26ff33318b51e20a80fb3",
        "productPrice": 4300,
        "productQuantity": 1,
        "productTotal": 4300
      }
    ]
  }
]

我想从ordershemas集合中引用“ orderItem.productId”到集合productchema。我只是保存对象ID,我想在屏幕上显示产品名称而不仅仅是ID。但是只要有重复项,返回的“产品”数组就不会重复,

1 个答案:

答案 0 :(得分:1)

您需要Order orderItem数组

orderSchema.aggregate([   
  { "$unwind": "$orderItem" },
  { "$lookup": {
    "from": 'productschemas',
    "localField": 'orderItem.productId',
    "foreignField": '_id',
    "as": 'product'
  }},
  { "$unwind": { "path": "$product", "preserveNullAndEmptyArrays": true }},
  { "$group": {
    "_id": "$_id",
    "product": { "$push": "$product" },
    "orderItem": { "$push": "$orderItem" },
    "orderClientName": { "$first": "$orderClientName" },
    "orderContact": { "$first": "$orderContact" }
  }}
])