繁体   English   中英

想要通过mongodb node.JS中的_id获取引用集合的对象

[英]Want to get object of reference collection by _id in mongodb node.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字段。 猫鼬然后可以发出第二个查询以根据需要解析引用的字段。

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

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

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

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

前提是您将branch。$ id保存为架构对象类型。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM