Thursday, October 20, 2022

[FIXED] How to set character limits in content in ejs template

Issue

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.


Solution

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



Answered By - Yosvel Quintero
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.