How can I get data referencing form one collection

2020-04-11 06:29发布

问题:

router.get('/productSelect', (req, res, next) =>{
    productSchema.aggregate([   
        { $lookup:
            {
                from: 'supplierSchema',
                localField: 'supplierId',
                foreignField: '_id',
                as: 'supplier'
            }
        }

    ], (err, productSchema) =>{
        if(err) res.json(err);
        else res.json(productSchema);
    });
});

I want to get data from collection

[
  {
    "_id": "5ba26ff33318b51e20a80fb3",
    "productExist": true,
    "productName": "Anything",
    "supplierId": "5b9d25064dcf2327b449ae1b",
    "brandId": "5b9d162a316e8d2660f26393",
    "categoryId": "5ba2509a6367372568b1ce6d",
    "productPrice": 222,
    "productQuantity": 320,
    "productMax": 3,
    "productMin": 4,
    "productTimeStamp": "2018-09-19T15:49:07.177Z",
    "__v": 0
  }
]

and replace the supplierId as supplierName from collection

[
  {
    "_id": "5b9d25064dcf2327b449ae1b",
    "supplierExist": true,
    "supplierName": "NBA World Wide",
    "supplierStatus": "Available",
    "supplierTimeStamp": "2018-09-15T15:28:06.971Z",
    "__v": 0
  }
]

回答1:

For making join with two table you have make sure that the type for both the fields i.e. localField and foriegnField should be the same.

Or

With mongodb 4.0 you can easily change the type of the String to ObjectId using $toObjectId aggregation

productSchema.aggregate([   
  { "$lookup": {
    "from": "supplierSchema",
    "let": { "supplierId": { "$toObjectId": "$supplierId" }},
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$_id", "$$supplierId"] }}}
    ]
    as: "supplier"
  }}
])