如何从一个函数中检索并传递来自多个Schema的数据

即时通讯新手在expressjs,并想知道如何检索和通过我的控制器中的多个架构的数据。

这里是假的,假装我想打开add_new_blog页面,下面是路由器;

router.get('/add_new_blog', BlogController.index); 

那么在BlogController.index我需要检索类别和标签模型。

 const Category = require('models/categorySchema'); const Tag = require('models/tagSchema'); module.exports = { index(req, res, next){ Category.find({}); Tag.find({}); // how to find/retrieve data from both Schema then i pass them to Views. res.render('/blog/blogForm'); } } 

问题是编码看起来像从两个检索数​​据,然后传递给视图?

你可以使用Promise.all() ,获取两个mongoose调用数据,然后渲染它。

 const categoryFind = Category.find({}).exec(); // exec() returns a Promise. const tagsFind = Tags.find({}).exec(); Promise.all(categoryFind, tagsFind).then((values) => { res.render('/blog/blogForm', { categories: values[0], tags: values[1] }); }); 

请注意,我在callback中呈现,这是因为mongoose调用是asynchronous的。 否则,您将在查询完成之前进行渲染。

这是一样的:

 Category.find({}, (err, catData) => { Tags.find({}, (err, tagsData) => { res.render('/blog/blogForm', { categories: catsData, tags: tagsData }); } }