Lepta Lepta - 1 year ago 227
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:

(err, posts) => {
if(err) return console.log(err);
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 Source

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

            preview: { $substr: [ "$data", 0, 50 ] }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download