This content originally appeared on DEV Community and was authored by Sandeep
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 faster as compare to simple finding collection. mongoose also say this its gives 10x faster 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.
This content originally appeared on DEV Community and was authored by Sandeep
Sandeep | Sciencx (2022-07-02T04:36:21+00:00) Get MongoDB data 10x faster using lean function in NodeJs. Retrieved from https://www.scien.cx/2022/07/02/get-mongodb-data-10x-faster-using-lean-function-in-nodejs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.