VOOZH about

URL: https://www.geeksforgeeks.org/mongodb/mongoose-schematype-prototype-index-api/

⇱ Mongoose SchemaType.prototype.index() API - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mongoose SchemaType.prototype.index() API

Last Updated : 23 Jul, 2025

Mongoose is a popular Node.js library for MongoDB, offering a powerful, schema-based solution to model application data. One of the key features of Mongoose is its ability to create indexes in MongoDB collections using the SchemaType.prototype.index() method. Indexes are important for optimizing query performance, especially with large datasets, and Mongoose allows us to define various types of indexes with ease.

What is Mongoose SchemaType.prototype.index() API ?

Mongoose SchemaType.prototype.index() is a method that is used to create an index on a field in a Mongoose schema. An index is a data structure that allows for efficient querying of data in a database. It can be created one or more fields in a collection to speed up queries that use those fields as search criteria. When an index is created on a field, the database creates a separate data structure that stores the values of that field and a reference to the document that contains each value.

Syntax:

SchemaType.prototype.index( options )

Parameters:

options (optional): An object that specifies the index configuration. This can include options such as:

  • unique: Ensures all values in the indexed field are unique.
  • sparse: Only indexes documents where the field exists.
  • expireAfterSeconds: Specifies a TTL (Time-To-Live) for the index to auto-remove documents after a set duration.
  • partialFilterExpression: Allows indexing based on specific conditions.

Return Type:

  • Returns a SchemaType object, which is the updated field configuration after applying the index.

Creating node application And Installing Mongoose:

Step 1. We can install this package by using this command.

npm install mongoose

Step 2. After installing the mongoose module, you can check your mongoose version in the command prompt using the command.

npm version mongoose

Step 3. After that, we can just create a folder and add a file for example index.js, To run this file we need to run the following command.

node index.js

Project Structure: The project structure will look like this:

👁 Image
 

Example 1: Creating Indexes on User Schema

In this example, we create a Mongoose schema for a user with a name, email, age, and address field. We then use the SchemaType.prototype.index() method to create various types of indexes on different fields in the schema.

After defining the schema and creating the indexes, we connect to a MongoDB database, create a new user document, and save it to the database. Finally, we log the newly created user's name.

Index.js

const mongoose = require("mongoose");
const { Schema } = mongoose;
mongoose.set("strictQuery", true);
const userSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
age: Number,
address: {
street: String,
city: String,
state: String,
zip: String,
},
});

// Creating indexes on the email and age fields
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ age: 1 });

// Creating a compound index on the address fields
userSchema.index({ "address.city": 1, "address.state": 1 });

// Creating a text index on the name and address fields
userSchema.index({
name: "text",
"address.street": "text",
"address.city": "text",
"address.state": "text",
});

// Creating a 2dsphere index on the address field for
// geo-spatial queries
userSchema.index({ "address.coordinates": "2dsphere" });

// Creating a hashed index on the name field for
//efficient sharding
userSchema.index({ name: "hashed" });

// Creating a partial index on the age field for documents
// where the age field is less than or equal to 30
userSchema.index(
{ age: 1 },
{ partialFilterExpression: { age: { $lte: 30 } } }
);

const User = mongoose.model("User", userSchema);

// Connecting to a MongoDB database and creating a new user
mongoose
.connect("mongodb://localhost:27017/geeksforgeeks",
{ useNewUrlParser: true })
.then(() => {
console.log("Connected to MongoDB");

const newUser = new User({
name: "John Doe",
email: "johndoe@example.com",
age: 25,
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
zip: "12345",
},
});

return newUser.save();
})
.then((user) => {
console.log(`Created new user: ${user.name}`);
mongoose.connection.close();
})
.catch((err) => console.error(err));

Steps to run the code:

1. Confirm if we have installed the mongoose module.

npm install mongoose

2. Run the code with the following command:

node index.js

Output:

👁 Image

Explanation: The database will create the specified indexes on the email, age, address, and other fields for faster queries.

Example 2: Creating Unique Index on Subdocument Array

In this example, we define a movieSchema with a subdocument array field called actors. We then create a unique index on the actors.name field using the index() method. This index will enforce uniqueness on the actors.name field within the actors subdocument array.

We then create a new movie with a duplicate actor name and attempt to save it to the database. Since the actors.name field is unique, MongoDB will throw a duplicate key error and the save operation will fail.

Index.js

const mongoose = require("mongoose");
const { Schema } = mongoose;
mongoose.set("strictQuery", true);
const movieSchema = new Schema({
title: {
type: String,
required: true,
},
actors: [
{
name: {
type: String,
required: true,
},
character: {
type: String,
required: true,
},
},
],
});

// Creating a unique index on the 'actors.name' field within
// the 'actors' subdocument array
movieSchema.index({ "actors.name": 1 }, { unique: true });

const Movie = mongoose.model("Movie", movieSchema);

// Connecting to a MongoDB database and creating a new user
mongoose
.connect("mongodb://localhost:27017/geeksforgeeks",
{ useNewUrlParser: true })
.then(() => {
console.log("Connected to MongoDB");

const newMovie = new Movie({
title: "The Avengers",
actors: [
{ name: "Robert Downey Jr.", character: "Iron Man" },
{ name: "Chris Evans", character: "Captain America" },
{ name: "Robert Downey Jr.", character: "Tony Stark" },
// Duplicate actor name
],
});

return newMovie.save();
})
.then((movie) => {
console.log(`Created new movie: ${movie.title}`);
mongoose.connection.close();
})
.catch((err) => console.error(err));

Steps to run the code: Run the following command:

node index.js

Output:

👁 Image

Best Practices for Indexing in Mongoose

  1. Index Frequently Queried Fields: Always index fields that are frequently used in search queries or sort operations.
  2. Use Compound Indexes Wisely: Combine indexes on multiple fields to optimize complex queries, but be mindful of the index size.
  3. Avoid Over-Indexing: Too many indexes can slow down write operations. Only index the fields that matter most for query performance.
  4. Leverage TTL Indexes for Expiration: Use expireAfterSeconds to automatically delete documents after a set duration, useful for session data, logs, etc.
  5. Monitor Index Usage: MongoDB provides tools to analyze index efficiency, so monitor and optimize indexes regularly.

Conclusion

The SchemaType.prototype.index() method in Mongoose is a powerful feature that helps improve query performance by creating various types of indexes. Whether you're dealing with single-field indexes, compound indexes, text search, or geospatial queries, Mongoose provides an easy-to-use API for managing indexes in MongoDB. By following best practices for indexing, we can ensure that your application remains efficient and scalable.

Comment
Article Tags:

Explore