我认为这与javascript处理父/子变异的方式有关...但是我不确定。
代码:
router.get('/:id/articles', authenticate, async (req, res, next) => {
try {
let user = await db.getUserIdName(req.params.id);
if (user) {
articles = await db.getUserArticles(req.params.id);
user.articles = articles;
// select categories.id from `articles_categories_relationship` join `categories` on `articles_categories_relationship`.`article_id` = `categories`.`id` where `articles_categories_relationship`.`category_id` = '1'
let finalUser = Object.assign({}, user);
user.articles.forEach(async (article, index) => {
finalUser.articles[index].categories = [];
const newCategories = await dbArticles.getCategoriesByArticleId(
article.id
);
newCategories.forEach(async category => {
await finalUser.articles[index].categories.push(category.id);
});
console.log(newCategories);
console.log(finalUser.articles[index].categories);
});
console.log(finalUser);
// console.log(user.articles[0]);
res.status(200).json(finalUser);
} else {
next({ code: 400 });
}
} catch (err) {
next(err);
}
});
这是console.log()
的输出...
注意:请参见categories
{ id: 1,
display_name: 'RandomBlogger',
articles:
[ { id: 1,
user_id: 1,
cover_page: 'https://coverpage1.com/',
title: 'Hello World',
link: 'https://helloworld.com/',
categories: [] },
{ id: 2,
user_id: 1,
cover_page: 'https://i.imgur.com/zbg9mtf.png',
title: 'Lambda Strikes Down Students With New Build Week',
link: '',
categories: [] },
{ id: 3,
user_id: 1,
cover_page: '',
title: 'Deadlines?-?Bad reason for bad code.',
link: 'https://medium.com/mindorks/deadlines-bad-reason-for-bad-code-d3d5fe22f3ff',
categories: [] } ] }
::1 - GET /users/1/articles HTTP/1.1 200 526 - 7.632 ms
[ { id: 1 }, { id: 3 } ]
[ 1, 3 ]
[ { id: 2 } ]
[ 2 ]
[ { id: 1 } ]
[ 1 ]
这是我对console.log()
的输出的期望...
注意:请参见categories
{ id: 1,
display_name: 'RandomBlogger',
articles:
[ { id: 1,
user_id: 1,
cover_page: 'https://coverpage1.com/',
title: 'Hello World',
link: 'https://helloworld.com/',
categories: [ 1, 3 ] },
{ id: 2,
user_id: 1,
cover_page: 'https://i.imgur.com/zbg9mtf.png',
title: 'Lambda Strikes Down Students With New Build Week',
link: '',
categories: [ 2 ] },
{ id: 3,
user_id: 1,
cover_page: '',
title: 'Deadlines?-?Bad reason for bad code.',
link: 'https://medium.com/mindorks/deadlines-bad-reason-for-bad-code-d3d5fe22f3ff',
categories: [ 1 ] } ] }
::1 - GET /users/1/articles HTTP/1.1 200 526 - 7.632 ms
[ { id: 1 }, { id: 3 } ]
[ 1, 3 ]
[ { id: 2 } ]
[ 2 ]
[ { id: 1 } ]
[ 1 ]
如果有人可以向我解释为什么退出父forEach
循环后为什么不保存这些更改,我将非常感谢