Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
Prats Avatar asked Mar 28 '26 08:03

Prats


1 Answers

I got it working using this:

// GLOBAL ARRAYS FOR STORING COLLECTION DATA
var collectionOne = [];
var collectionTwo = [];
app.get('/', function(req, res){
  MongoClient.connect("mongodb://localhost:27017/michael", function(err, db) {
    if(!err) {
      console.log("We are connected");
    }
    db.collection("collectionOne", function(err, collection) {
      collection.find().sort({order_num: 1}).toArray(function(err, result) {
        if (err) {
          throw err;
        } else {
          for (i=0; i<result.length; i++) {
            collectionOne[i] = result[i];
          }
        }
      });
      db.collection("collectionTwo", function(err, collection) {
        collection.find().sort({order_num: 1}).toArray(function(err, result) {
          if (err) {
            throw err;
          } else {
            for (i=0; i<result.length; i++) {
              collectionTwo[i] = result[i];
            }
          }
        });
      });
      // Thank you aesede!
      res.render('index.html', {
        collectionOne: collectionOne,
        collectionTwo: collectionTwo
      });
    });
  });
});

Now, for some reason when Node restarts, and I hit refresh, it doesn't render HTML into the front-end. However, any subsequent refresh renders the page correctly.

like image 75
zickonezero Avatar answered Mar 29 '26 21:03

zickonezero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!