如何获取从一个集合到另一个集合的数据引用?蒙古数据库 [英] How can I get data referencing form one collection to another? Mongodb

查看:14
本文介绍了如何获取从一个集合到另一个集合的数据引用?蒙古数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
    });
});

我想从集合中获取数据

[
  {
    "_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
  }
]

并将supplierId替换为collection中的supplierName

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
  }
]

推荐答案

要与两个表进行连接,请确保两个字段的类型,即 localFieldforiegnField 应该是一样的.

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.

或者

使用 mongodb 4.0,您可以使用 $toObjectId 聚合

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"
  }}
])

这篇关于如何获取从一个集合到另一个集合的数据引用?蒙古数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆