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?
问题是从两者检索数据然后将其传递给视图的编码是什么样的?
1 个解决方案
#1
2
You can use Promise.all(), get the two mongoose calls data and then render it.
你可以使用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] });
});
Notice that I render inside the callback, that is because mongoose calls are asynchronous. Otherwise you will be rendering before the queries have completed.
请注意,我在回调内部渲染,这是因为mongoose调用是异步的。否则,您将在查询完成之前进行渲染。
That is the same as:
这与以下相同:
Category.find({}, (err, catData) => {
Tags.find({}, (err, tagsData) => {
res.render('/blog/blogForm', { categories: catsData, tags: tagsData });
}
}
#1
2
You can use Promise.all(), get the two mongoose calls data and then render it.
你可以使用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] });
});
Notice that I render inside the callback, that is because mongoose calls are asynchronous. Otherwise you will be rendering before the queries have completed.
请注意,我在回调内部渲染,这是因为mongoose调用是异步的。否则,您将在查询完成之前进行渲染。
That is the same as:
这与以下相同:
Category.find({}, (err, catData) => {
Tags.find({}, (err, tagsData) => {
res.render('/blog/blogForm', { categories: catsData, tags: tagsData });
}
}