StackOvernizer StackOvernizer - 21 days ago 11
Node.js Question

can't pass mongo population onto ejs page

I've been using mongoose to successfully render information from the database on ejs pages. Now I want to render information that is populated (through mongo population) on a specific object. Is this even possible? I'm not having success so far

app.get('/profile', isLoggedIn, function(req, res) {
Event.find(function(err, services) {
if (err) return next(err);

services.forEach(function(service){

Event
.findOne({title: service.title})
.populate('user')
.exec(function (err, populated) {
if (err) return handleError(err);
if(!populated) console.log("failed")
else {
console.log('The creator is ' + populated.user.local.name);
service = populated;
}
});

});

res.render('./partials/profile.ejs', {user: req.user, status: status, badges: badgerinos, services: services}); // load the profile.ejs partial
});
});


The console.log shows the creator's name correctly but on the rendering page, the user field is undefined. What am I doing wrong?

Answer

Are you doing two queries for each Event? If you are trying to list all Events and populate the user-field it should be quicker to just go:

Event
.find({})
.populate('user')
.exec((err, services) => {
    if (err) return next(err);
    //Services are already populated
    res.render('./partials/profile.ejs', {user: req.user, status: status, badges: badgerinos, services: services}); // load the profile.ejs partial
});
Comments