如何在Express.js上的路由器中对数据库使用少量查询

时间:2017-11-21 20:33:56

标签: node.js express mongoose

我有路由器,需要从两个不同的集合中获取数据。如何在没有回调的情况下执行此操作?

router.get('/menu/:id', function(req, res, next) {
    var product = Product.find({menu: req.params.id}, function(err, products){
        var menu = Menu.findOne({_id: req.params.id}, function(err, menu){
            res.render('menu', {  
                user: req.user,
                csrfToken: req.csrfToken(),
                current_menu: menu,
                products: products
            });
        });
    });
});

1 个答案:

答案 0 :(得分:1)

正如@tadman所说,使用async/await

会很有用
router.get('/menu/:id', async function(req, res, next) {
   var products= await Product.find({menu: req.params.id}).exec();
   var menu = await Menu.findOne({_id: req.params.id}).exec();
        res.render('menu', {  
            user: req.user,
            csrfToken: req.csrfToken(),
            current_menu: menu,
            products: products
        });
  });
});