我有一系列故事,现在我想循环遍历它,获取每个键和值并将其传递给渲染。在Stories数组中,我有一个名为story_category_id
的字段。我只能在函数中传递一个ID,我需要获取所有收集故事的所有类别。
router.get('/', (request, response, next) => {
Story.getAllStories((error, stories) => {
StoryCategory.getAllStoryCategories((error, story_categories) => {
Story.getStoryCategoryById(WHATTOPUTHERE, (error, story_category) => {
response.render('./stories/all_stories', {
section_name: "All Stories",
stories: stories,
story_category: story_category,
story_categories: story_categories,
});
})
});
});
});
答案 0 :(得分:0)
我认为你应该摆脱回调风格并学会使用承诺。此外,当您需要处理ID数组时,您的函数只需要module.exports.getStoryCategoryById
只有一个ID。所以你可以像这样改进你的功能..
my-module.js
// Get all stories
module.exports.getAllStories = () => Story.find({})
.sort([['story_title', 'ascending']]).exec();
// Get all story categories
module.exports.getAllStoryCategories = () => StoryCategory.find({})
.sort([['story_category_title', 'ascending']]).populate('story_category_title').exec();
module.exports.getStoryCategoryById = (id) => StoryCategory.findById(id)
.exec();
然后你可以像这样定义你的路由器......
router.get('/', async (request, response, next) => {
try {
const stories = await Story.getAllStories();
const story_categories = await StoryCategory.getAllStoryCategories();
// mapping stories to take out all the categories within that story.
const story_category = await Story
.getStoryCategoryById(stories[0].story_category_id);
response.render('./stories/all_stories', {
section_name: "All Stories",
stories, // each story will have its own category..
story_category,
story_categories,
});
} catch(err) {
next(err)
}
});
从以前的版本更改了这一行代码,现在它只会加载一个故事类别。
const story_category = await Story
.getStoryCategoryById(stories[0].story_category_id);