想在mongobd node.JS中通过_id得到参考集合的对象

我想通过引用id集合来获取特定logging的所有细节。

{ "_id" : ObjectId("586c8bf63ef8480af89e94ca"), "createdDate" : ISODate("2017-01-04T05:45:26.945Z"), "branch" : { "$ref" : "branchmst", "$id" : "5864ac80fa769f09a4881791", "$db" : "eviral" }, "__v" : 0 } 

这是我的collectionslogging。 我需要所有来自“branchmst”集合的详细信息,其中“_id”是“5864ac80fa769f09a4881791”。

你的集合是一个使用手工引用的例子,即在另一个文档DBref中包含一个文档的_id字段。 然后,Mongoose可以发出第二个查询来根据需要parsing引用的字段。

第二个查询是使用具有$lookup操作符的聚合方法,该操作将在同一个数据库中执行左外连接到“branchmst”集合,以在来自“已join”集合的文档中进行过滤以进行处理:

 MyModel.aggregate([ { "$match": { "branch": "5864ac80fa769f09a4881791" } }, { "$lookup": { "from": "branchmst", "localField": "branch", "foreignField": "_id", "as": "branchmst" } }, { "$unwind": "$branchmst" } ]) 

你也可以在Mongoose中使用populate()函数,因为你已经明确定义了模型定义中的ref

 var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.Types.ObjectId; // define the main schema var mySchema = mongoose.Schema({ createdDate: { type: Date, default: Date.now }, branch: { type: ObjectId, ref: 'Branch' } }) // define the branch schema var branchSchema = mongoose.Schema({ name: String, address: String }) // compile the models var MyModel = mongoose.model('MyModel', mySchema), Branch = mongoose.model('Branch', branchSchema); // populate query MyModel.find({ "branch": "5864ac80fa769f09a4881791" }) .populate('branch') .exec(function (err, docs) { //console.log(docs[0].branch.name); console.log(docs); }); 

只要你保存你的分支。$ id作为Schema对象的types。

  yourRecord.find({}).populate(branch.$id).exec(function(err, data){ console.log(data) })