简体   繁体   中英

How can I find and display data from two collections at the same time?

I am making a node app where two collections are being stored and I need to loop through all the documents of each collection and then pass it to handlebars to render each document. Only one of the documents is being rendered and the other one isn't. I am using express-handlebars for rendering the front end.

Here is the relevant code for handlebars:

 <div class="tc"> <ul> {{#each drop}} <li>{{teamName}} : {{totalScore}} Points <span><i class="fas fa-pen"></i></span></li> {{/each}} </ul> <ul> {{#each pass}} <li>{{teamName}} : {{totalScore}} Points <span><i class="fas fa-pen"></i></span></li> {{/each}} </ul> </div> 

I tried two things on the server side:

1) Errors: Can't Set headers after they are set.

 app.get('/history', (req, res) => { Drop.find() .sort({ totalScore: 'desc' }) .then(drop => { res.render('history', { hideFooter: false, drop: drop }); }) Pass.find() .sort({ totalScore: 'desc' }) .then(pass => { res.render('history', { hideFooter: false, pass: pass }); }) }); 

2) Only Pass is being rendered on the front end and not drop is not rendered.

 app.get('/history', (req, res) => { Drop.find() .sort({ totalScore: 'desc' }) .then(drop => { Pass.find() .sort({ totalScore: 'desc' }) .then((pass, drop) => { res.render('history', { hideFooter: false, pass: pass, drop: drop }); }) }); }); 

UPDATE: I also tried async.parallel

 var async = require('async'); async.parallel([ Drop.find() .sort({ totalScore: 'desc' }), Pass.find() .sort({ totalScore: 'desc' }) ], function(results) { res.render('history', { hideFooter: false, pass: pass, drop: drop }); }); 

the problem could be with the drop parameter that you added in the second promise, try removing that

 app.get('/history', (req, res) => { Drop.find() .sort({ totalScore: 'desc' }) .then(drop => { Pass.find() .sort({ totalScore: 'desc' }) .then(pass => { res.render('history', { hideFooter: false, pass: pass, drop: drop }); }) }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM