I want to apply a truncate(string, words) function to the 'body' field of all Article documents returned by a mongoose query. An example would be as follows:
Article.find({})
.sort({'meta.created': 'desc'})
.limit(6)
.exec(function(err, articles) {
// Truncate the article.body field on each articles here?
res.render(articles: articles});
});
With a simple truncate function something like:
function truncate(string, words) {
var value_arr = string.split( ' ' );
if( words < value_arr.length ) {
value = value_arr.slice(0, words).join( ' ' );
}
return value;
}
How can I apply this function to each articles body field (retaining the articles structure for use in a template)? Thanks in advance.
The proper way, I believe, would be to add a truncatedBody property to your Article, and implement the truncate method as a static:
Article.methods.setTruncatedBody = function(limit){
//If truncatedBody is already computed, don't do anything
if(this.truncatedBody)
return;
var value_arr = body.split( ' ' );
if( limit < value_arr.length ) {
this.truncatedBody = value_arr.slice(0, words).join( ' ' );
}
else
this.truncatedBody = body;
}
Then, in your controller:
Article.find({})
.sort({'meta.created': 'desc'})
.limit(6)
.exec(function(err, articles) {
for(var article in articles)
article.setTruncatedBody(5);
res.render(articles: articles});
});