javascript - 如何为 View 提供子字符串对象? Express.js

标签 javascript node.js express

嗨,我刚刚开始编程,我正在尝试使用 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),
    };
}

只需将 titlecontent 的键名称更改为您正在使用的任何名称,因为您没有说明数据的外观。

或者您可以更改此设置:

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/

相关文章:

javascript - 如何将 onchange 绑定(bind)到每个单选按钮组

javaScript - ES6 中的多重继承,

node.js - 一个字段在 Mongoose 模式中可以有哪些选项?

node.js - Keycloak:使用 nodeJS 的 authZ

javascript - 从数据库中获取最新5条数据

javascript - 使用 express 启用 http 压缩

node.js - 仅 http cookie + token : double job?

javascript - 如何设置加载 JSON 层的最小缩放?

javascript - 将数组对象显示为表格

javascript - 如何将回调返回值分配给 Mongoose 中的变量?