简体   繁体   中英

Want to get object of reference collection by _id in mongodb node.JS

I want to get all detail of particular record by reference id collection.

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

This is my collection record. I need to all detail from "branchmst" collection where "_id" is "5864ac80fa769f09a4881791".

Your collection is an example of using manual references ie including one document's _id field in another document DBref . Mongoose can then issue a second query to resolve the referenced fields as needed.

The second query would be to use the aggregate method which has the $lookup operator that will perform a left outer join to "branchmst" collection in the same database to filter in documents from the "joined" collection for processing:

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

You can also use the populate() function in Mongoose given you have explicitly defined the refs in your Model definition ie

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

provided you saved your branch.$id as type Schema Object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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