希望通过mongodb节点中的_id获取引用集合的对象.JS



我想通过引用id集合获得特定记录的所有细节。

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

这是我的收藏记录。我需要"branchmst"集合中的所有细节,其中"_id"是"5864ac80fa769f09a4881791"。

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

第二个查询将使用聚合方法,该方法具有$lookup运算符,该运算符将对同一数据库中的"branchmst"集合执行左外部联接,以过滤"联接"集合中的文档进行处理:

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

您也可以在Mongoose中使用populate()函数,前提是您已经在模型定义中明确定义了refs,即

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为架构对象类型。

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

最新更新