Saurabh Sharma Saurabh Sharma - 3 months ago 22
Node.js Question

How to set character limits in content in ejs template

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.

Answer

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