DEV Community

Cover image for Make Express Server fast Request & Response Using Indexing in mongoDB
Deepak Jaiswal
Deepak Jaiswal

Posted on

3 2 1 1 1

Make Express Server fast Request & Response Using Indexing in mongoDB

Hey Developers Today we discuss on topic how we fast our server.
so we learn about indexing in express of mongoose.

normally we can make schemas like

const {Schema,model}=require('mongoose');

const userSchema=new Scheam({
   name:{
      type:String,
      required:true
   },
   email:{
      type:String,
      required:true,
      unique:true
   },
   isDeleted:{
      type:Boolean,
      default:false
   },
});

const UserModel=model('User',userSchema);
module.export=UserModel;
Enter fullscreen mode Exit fullscreen mode

normally we can use to check user on their email. in mongoDB unique

field auto index but other field not index.

const user=await User.findOne({email: "sandeep@gmal.com" , isDeleted:false});
Enter fullscreen mode Exit fullscreen mode

In above query of mongoose it takes more time because isDeleted field not indexed. so we make isDeleted field as index. so refactor model code.

const {Schema,model}=require('mongoose');

const userSchema=new Scheam({
   name:{
      type:String,
      required:true,
      index:true
   },
   email:{
      type:String,
      required:true,
      unique:true
   },
   isDeleted:{
      type:Boolean,
      default:false,
      index:true
   },
});

const UserModel=model('User',userSchema);
module.export=UserModel;
Enter fullscreen mode Exit fullscreen mode

we make name is also in index because in searching query we check from name thats why we make as indexed field.
after make as index field you can see in mongodb document indexed field.

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay