How to set character limits in content in ejs template

不羁岁月 提交于 2021-02-08 08:13:02

问题


I am fetching content from Mognodb in EJS template. I have description field which contains more then 500 characters, but I want to show only 50 Characters in my view.

Can anyone tell me how to do it.


回答1:


In the view you can use JavaScript String.prototype.substring():

<%= description.substring(0, 50) %>

Within MongoDB you can use $substr to return a new field with the desired 50 characters:

db.collectionName.aggregate([{
    $project: {
        title: 1,
        shortDescription: {
            $substr: ["$description", 0, 50]
        }
    }
}]);

Note that in the code example I am using a collection named collectionName and fields names like title and description.. This way will be returned only title and shortDescription with a limit to 50 characters to use in the view



来源:https://stackoverflow.com/questions/39094358/how-to-set-character-limits-in-content-in-ejs-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!