[英]how to retrieve and pass data from more than 1 Schema in a function
im newbie in expressjs and wondering how to retrieve and pass data from more than 1 schema in my controller. 我是expressjs中的新手,想知道如何从控制器中的多个模式中检索和传递数据。
here is the case, pretend i wanna open add_new_blog page and below is the router; 就是这种情况,假装我想打开add_new_blog页面,下面是路由器;
router.get('/add_new_blog', BlogController.index);
well then in BlogController.index i need to retrieve Category and Tag Models. 那么在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');
}
}
The Question is What the coding will look like to retrieve the data from both then pass it to the view? 问题是,从两者中检索数据然后将其传递给视图的编码将是什么样的?
You can use Promise.all() , get the two mongoose calls data and then render it. 您可以使用Promise.all() ,获取两个猫鼬调用数据,然后进行渲染。
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] });
});
Notice that I render inside the callback, that is because mongoose calls are asynchronous. 注意,我在回调内部进行渲染,这是因为猫鼬调用是异步的。 Otherwise you will be rendering before the queries have completed. 否则,您将在查询完成之前进行渲染。
That is the same as: 等同于:
Category.find({}, (err, catData) => {
Tags.find({}, (err, tagsData) => {
res.render('/blog/blogForm', { categories: catsData, tags: tagsData });
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.