【问题标题】:Want to get object of reference collection by _id in mongodb node.JS想通过 _id 在 mongodb node.JS 中获取引用集合的对象
【发布时间】:2017-05-19 22:47:58
【问题描述】:

我想通过引用 id 集合获取特定记录的所有详细信息。

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

这是我的收藏记录。我需要“_id”为“5864ac80fa769f09a4881791”的“branchmst”集合中的所有详细信息。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    如果您将 branch.$id 保存为类型 Schema Object。

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

    【讨论】:

    • 什么是“provideid”?
    • 它是您传递的 id 的变量名称。如果您想查找任何特定文档,否则请继续不使用 id :providedid 。它将填充所有记录
    • var objModel = require('../models/logModel'), objModel.find(function (err, results) { if (err) { return res.send(500, { error: err }); } results.find().populate(branch.$id).exec(function (err, data) { console.log(data) }) });是这样吗??
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-06
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多