我正在 EJS 模板中从 Mognodb 获取内容。 我的描述字段包含超过 500 个字符,但我只想在 View 中显示 50 个字符。
谁能告诉我该怎么做
最佳答案
在 View 中您可以使用 JavaScript String.prototype.substring() :
<%= description.substring(0, 50) %>
在 MongoDB 中,您可以使用 $substr返回一个包含所需 50 个字符的新字段:
db.collectionName.aggregate([{
$project: {
title: 1,
shortDescription: {
$substr: ["$description", 0, 50]
}
}
}]);
请注意,在代码示例中,我使用名为 collectionName
的集合以及诸如 title
和 description
之类的字段名称。这种方式将是仅返回 title
和 shortDescription
, View 中使用的字符数限制为 50 个
关于node.js - 如何设置ejs模板内容的字符限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39094358/