I'm trying to load and display some information from mongo db. My site runs on node.js / express.
I have two tables, the first is palettes, which i load and display all of, and that works just fine. But for each palette, i have a list of examples. I want to loop through each palette, and get all the examples for that palette.
I'm definitely doing something wrong, I think it's because the find() method is asyncronous, so my data is getting sent before it pulls the extra data. But I can't put the render function in the callback for the examples because it's run multiple times.
In PHP I used to be able to pull data from another table and connect it to the first one based on a common column, but I'm not sure how to do this here, which is why I tried to do it manually with a loop.
/* GET palette database main page. */
router.get('/', function(req, res, next) {
console.log('rendering test page');
var Palette = require('../models/paletteDatabase');
//load all palettes
Palette.find({}, function(err, palettes) {
if (err) return next(err);
var PaletteExamples = require('../models/paletteExamples');
for (var i = 0; i < palettes.length; i++) {
//split the colors into an array
palettes[i].colorsArray = palettes[i].colors.split(',');
PaletteExamples.find({paletteId: palettes[i]._id}, function(err, result) {
if (err) return next(err);
palettes[i].examples=result;
});
}
res.render('palette-database', {
title: 'Palette List',
palettes: palettes,
css: 'palette-db',
js: 'palette-db'
});
});
});