Prats Prats - 11 months ago 72
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 Source

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})
    .exec(function(err, testDocMaster) {
        // testDocMaster.docId is populated with the full testDoc for the
        // matching _id