MongoDB:如何解决客户端上的DBRef?

我是mongodb的新手,很抱歉,如果这个问题是愚蠢的:我已经拉了一个文件,结构如下:

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

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

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

你可以用$lookup操作符来解决这个问题。 考虑下面的聚合pipe道:

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

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

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

mongoose填充