簡體   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