嗨,我刚刚开始编程,我正在尝试使用 Express.js 和 Mongoose 创建一个非常简单的博客。通过这段代码,我在博客的首页上打印数据库中的 6 篇文章(简单的文章架构:标题、内容和用户)。但是我如何才能不显示整个内容,而只显示内容中的前 100 个字母。我如何将其传递到 View ?
index: (req, res) => {
Articles.find({}).limit(6).populate('author').then(articles => {
res.render('home/index', { articles: articles})
})
最佳答案
而不是这个:
res.render('home/index', { articles: articles });
你必须使用:
res.render('home/index', { articles: articles.map(shorten) });
并实现 shorten()
函数,如下所示:
function shorten(article) {
return {
title: article.title,
content. article.content.slice(0, 100),
};
}
只需将 title
和 content
的键名称更改为您正在使用的任何名称,因为您没有说明数据的外观。
或者您可以更改此设置:
res.render('home/index', { articles: articles.map(shorten) });
类似于:
articles.forEach(article => {
article.content = article.content.slice(0, 100);
});
res.render('home/index', { articles: articles });
如果您确定稍后不需要 articles
数组中的原始值。
关于javascript - 如何为 View 提供子字符串对象? Express.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43211777/