【问题标题】:MongoDB: How to resolve DBRef on client-side?MongoDB:如何在客户端解析 DBRef?
【发布时间】:2016-06-14 02:58:50
【问题描述】:

我是 mongodb 新手,如果这个问题很愚蠢,很抱歉:我提取了一个具有以下结构的文档:

{
"_id" : ObjectId("575df70512a1aa0adbc2b496"),
"name" : "something",
"content" : {
    "product" : {
        "$ref" : "products",
        "$id" : ObjectId("575ded1012a1aa0adbc2b394"),
        "$db" : "mdb"
    },
    "client" : {
        "$ref" : "clients",
        "$id" : ObjectId("575ded1012a1aa0adbc2b567"),
        "$db" : "mdb"
    }
}

我指的是productsclients 集合中的文档。我读过可以在客户端 (https://stackoverflow.com/a/4067227/1114975) 解决这些 DBRefs。

我该怎么做?我想避免查询这些对象并将它们嵌入到文档中。谢谢

【问题讨论】:

    标签: node.js mongodb aggregation-framework


    【解决方案1】:

    您可以使用 $lookup 运算符解决此问题。考虑以下聚合管道:

    // Execute aggregate, notice the pipeline is expressed as an Array
    collection.aggregate([
        {
            "$lookup": {
                "from": "product",
                "localField": "content.product.$id",
                "foreignField": "_id",
                "as": "products"
            }
        },
        {
            "$lookup": {
                "from": "clients",
                "localField": "content.client.$id",
                "foreignField": "_id",
                "as": "clients"
            }
        },
      ], function(err, result) {
        console.log(result);
    });
    

    【讨论】:

    【解决方案2】:

    我会考虑使用Mongoose,它可以帮助您解决这个问题和其他问题。在这种情况下,您可以使用类似:

    Collection.find({}).populate('products').populate('clients')
              .exec(function(err, books) {...});
    

    Mongoose populate

    【讨论】:

      猜你喜欢
      • 2012-04-02
      • 1970-01-01
      • 2022-06-20
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      相关资源
      最近更新 更多