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)
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)
}
}
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)
}
}
when we use lean function we cannot modify document value and save it.
Top comments (6)
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.
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
thanks for mentioning this here, I will have a deeper look into that as well.
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 ^^).
You are right. Thank you.
Here createdBy is reference of user model.
Thank you.