Learn How To Power Up Your MongoDB Or Mongoose With Few Tricks.

Image for post

Photo by  Benjamin Sow on  Unsplash

Last year, somewhere around Christmas, I started my journey as a NodeJS developer with MongoDB. I know in starting. I made many rookie mistakes and spend plenty of hours in StackOverflow and GitHub to find an appropriate solution. After several exhausting experiences. I find small but very useful tricks in MongoDB or mongoose.

1. lean()

When you execute any query in mongoose before the result, mongoose performs hydrate() a model function, which is used to create a new document from existing raw data, pre-saved in the DB. The returned document Is an instance of Mongoose Document class which is much heavy because they have a lot of internal state for change tracking. **lean()**create a shortcut from thehydrate()function and make queries faster and less memory-intensive but the return documents are plain old JavaScript objects (POJOs) not mongoose documents.

// Module that estimates the size of an object in memory
const sizeof = require('object-sizeof');

const normalDoc = await MyModel.findOne();
// To enable the `lean` option for a query, use the `lean()` function.
const leanDoc = await MyModel.findOne().lean();

sizeof(normalDoc); // >= 1000
sizeof(leanDoc); // 86, 10x smaller!

#nodejs #javascript #mongodb #mongoose

7 Simple MongoDB/Mongoose Tips Make Your Code Faster
2.50 GEEK