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.
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
In my case, I was iterating through the keys in the DB so (using the top answer) this is what I did:
<%= users[i].password.substring(0, 6)+"..."%>
In this case, 'users' is the collection in MongoDB, I'm retrieving the password and only showing 6 characters plus '...' to show that the password is actually longer.