DEV Community

Cover image for Get MongoDB data 10x smaller & faster using lean function in NodeJs
Deepak Jaiswal
Deepak Jaiswal

Posted on

9 3

Get MongoDB data 10x smaller & faster using lean function in NodeJs

sometimes, i am finding data in mongoose collection it give mongoose document but when we use lean function in find collection it gives response 10x smaller and faster as compare to simple finding collection. mongoose also say this its gives 10x smaller response.

product.model.js

const mongoose = require("mongoose")

const ProductSchema = new mongoose.Schema({
    name:{
        type:String,
        required:true,
                index:true,
        trim:true
    },
        createdBy:{
                type:mongoose.Types.Schema.ObjectId,
                ref:'user',
                required:true
        },
    color:{
        type:String,
        required:true,
        trim:true
    },
    ram:{
        type:String,
        required:true
    },
    rom:{
        type:String,
        required:true
    },
    price:{
        type:String,
        required:true
    },
    qty:{
        type:String,
        required:true,
        default:1
    },
    displaySize:{
        type:String,
        required:true
    },
    frontCamera:{
        type:String,
        required:true
    },
    rearCamera:{
        type:String,
        required:true
    },
    battery:{
        type:String,
        required:true
    },
    processor:{
        type:String,
        required:true
    },
    imageUrl:{
        type:String,
        required:true
    },
    modelNumber:{
        type:String,
        required:true
    },
    modelName:{
        type:String,
        required:true
    },
    operatingSystem:{
        type:String,
        required:true
    },
    warrenty:{
        type:String,
                default:"6 months"
    },
    addDate:{
        type:Date,
                default:Date.now
    }
})

module.exports = mongoose.model('Product',ProductSchema)
Enter fullscreen mode Exit fullscreen mode

product.controller.js

without lean function

module.exports.listAllProducts =async (req,res,next)=>{
  try{
    let products=await Product.find()
                .populate("createdBy").sort({addDate:-1})
        res.send(products);
  }catch(err){
    next(err)
  }
}
Enter fullscreen mode Exit fullscreen mode

with lean function

module.exports.listAllProducts =async (req,res,next)=>{
  try{
    let products=await Product.find().populate("createdBy")
               .lean().sort({addDate:-1})
        res.send(products);
  }catch(err){
    next(err)
  }
}
Enter fullscreen mode Exit fullscreen mode

when we use lean function we cannot modify document value and save it.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (6)

Collapse
 
abdurrkhalid333 profile image
Abdur Rehman Khalid

I am looking forward to working with the "lean" function as I have a lot of data and it takes a lot of time as well. So, I definitely have to try this function in my production environment as well.

Collapse
 
deepakjaiswal profile image
Deepak Jaiswal • Edited

lean function reduce the size of document so its affect the response.
check all details
mongoosejs.com/docs/tutorials/lean...
if you have more data you can use compression npm package

Collapse
 
abdurrkhalid333 profile image
Abdur Rehman Khalid

thanks for mentioning this here, I will have a deeper look into that as well.

Collapse
 
pyrsmk profile image
Aurélien Delogu

Just to point out that this is only a Mongoose trick to avoid model objects hydration after a query (just saying, because the title say something else ^^).

Collapse
 
deepakjaiswal profile image
Deepak Jaiswal

You are right. Thank you.

Collapse
 
deepakjaiswal profile image
Deepak Jaiswal

Here createdBy is reference of user model.
Thank you.

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay