Hi i am just starting with programming and i am trying to create a very simple blog with Express.js and Mongoose.Whit this code i am printing 6 articles from my database(simple Article Schema: title,content and user) on the front page of my blog.But how can i not display the whole content but just the start 100 letters from the content.How can i pass it to the view?
index: (req, res) => {
Articles.find({}).limit(6).populate('author').then(articles => {
res.render('home/index', { articles: articles})
})
Instead of this:
res.render('home/index', { articles: articles });
you'd have to use:
res.render('home/index', { articles: articles.map(shorten) });
and implement the shorten() function as follows:
function shorten(article) {
return {
title: article.title,
content. article.content.slice(0, 100),
};
}
Just change the key names for title and content to whatever you're using because you didn't say anything on how your data looks like.
Alternatively you can change this:
res.render('home/index', { articles: articles.map(shorten) });
to something like:
articles.forEach(article => {
article.content = article.content.slice(0, 100);
});
res.render('home/index', { articles: articles });
if you're sure that you won't need the original values in your articles array later.