Lepta Lepta - 23 days ago 14
Node.js Question

MongoDB (mongoose) retrieve substring

Let's say I have a blog with some very long posts.

So, I want to display a list of my posts in "preview mode", for instance only first 50 chars of text.

Simple answer is to do this:

Post.find(
(err, posts) => {
if(err) return console.log(err);
posts.forEach(
post => {
console.log('post preview:', post.data.substr(0,50) + '...');
}
)
}
)


This way we retrieve all data from specific collection.
If each post has more than 3 KB of data retrieving 30 posts seems very inefficient in terms of data transfer and processing.

So, I wondered if there is a way to retrieve already sliced string from DB?

Or at least do you have a better solution for my issue?

Answer

yes, you can use the $substr operator with a query like this :

db.collection.aggregate(
   [
     {
       $project:
          {
            preview: { $substr: [ "$data", 0, 50 ] }
          }
      }
   ]
)