Prats Prats - 1 month ago 18
Node.js Question

Fetch data from multiple collections in mongo

I have some collections shown like below which is holding relationships, relation between testMaster and testDoc is holding inside the testDocMaster

For eg:

testMaster {
_id: "Schema.Objectid",
name: "String" //master name
}

testDoc {
_id : Schema.ObjectId,
name: "String", //doc name
other datas
}

testDocMaster {
masterId: "_id of the testMaster table",
docId : "_id of the above testDoc"
}


For each master entry, we are expecting many relations,

what would be the best way to fetch the data from the testDoc table, if I have the masterId.

Answer

Assuming your testDocMaster schema uses ObjectId types that ref the other two collections you can use Mongoose's query population support to help with this:

TestDocMaster.findOne({ masterId: masterId})
    .populate('docId')
    .exec(function(err, testDocMaster) {
        // testDocMaster.docId is populated with the full testDoc for the
        // matching _id
    });
Comments