Reputation: 395
I currently have a profile page in which I show products from the "products" collection in my database. I also want to show a table on the page with results from the "payments" collection in my database but I'm unsure how to merge the queries?
The Products Query:
app.get('/profile', function(req, res){
Products.find({'username': req.user.username}).sort('-date').exec(function(err, docs){
res.render('profile', { title: 'Your Products',
products: docs,
firstname:req.user.firstName,
lastname:req.user.lastName,
email:req.user.email,
username:req.user.username,
});
});
});
The Payments Query:
app.get('/profile', function(req, res){
Payments.find({'paidby': req.user.username}).sort('-date').exec(function(err, docs){
res.render('profile', {payment: docs});
});
});
How can I load two of these queries into my profile page at the same time?
Upvotes: 0
Views: 60
Reputation: 1180
Use Promises for this type of problem. First of all you have to configure mongoose to use native promises:
mongoose.Promise = global.Promise;
Do this at startup. After you've done this you can do the following:
var paymentPromise = Payments.find({ 'paidby': req.user.username }).sort('-date').exec();
var productPromise = Products.find({ 'username': req.user.username }).sort('-date').exec();
Promise.all([paymentPromise, productPromise]).then(
docs => {
let paymentDocs = docs[0];
let productDocs = docs[1];
res.render('profile', {
title: 'Your Products',
products: productDoc,
payment: paymentDocs,
firstname: req.user.firstName,
lastname: req.user.lastName,
email: req.user.email,
username: req.user.username,
});
}
);
Upvotes: 1