How to pass a populated Mongoose object to rendering code?

In the following code from the routes.js file, I can successfully populate some links in a Mongoose object named Map . When I look at the page, the console prints a fully populated version of the popmap editor objects.

  app.get('/map/:id', function(req, res){ Map .findOne({ _id: req.map._id }) .populate('_editors') .run(function (err, popmap) { console.log('The editors are %s', popmap._editors); }); res.render('maps/show', { title: req.map.title, map: req.map }); }); 

However, I did not understand how to perform the population step so that the resulting object remains in the area for the rendering code. In other words, how do I pass a populated object to a Jade template instead of sending req.map ?

+4
source share
2 answers

The problem is that you are writing Mongoose code as if it were synchronous, but you need to call res.render inside the run callback function, because that is when the request is executed. In your example, the render function will be called before the result is returned by the query.

Alternatively, you can pass the popmap variable as a local variable into the view:

 app.get('/map/:id', function(req, res){ Map .findOne({ _id: req.map._id }) .populate('_editors') .run(function (err, popmap) { console.log('The editors are %s', popmap._editors); res.render('maps/show', { title: req.map.title, map: req.map, popmap: popmap // you can access popmap in the view now }); }); }); 
+5
source

Note that the fill task is asynchronous when the task is completed, as a result, the callback function will be called. Until then, the populated map will be unavailable.

Therefore, you need to do the rendering step inside the callback function.

  app.get('/map/:id', function(req, res){ Map .findOne({ _id: req.map._id }) .populate('_editors') .run(function (err, popmap) { console.log('The editors are %s', popmap._editors); res.render('maps/show', { title: popmap.title, map: popmap }); }); }); 
+3
source

Source: https://habr.com/ru/post/1389206/


All Articles