Open In App

Mongoose SchemaType.prototype.index() API

Last Updated : 16 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: The method takes only one parameter:

  • options (optional): An object that specifies the options for the index. This parameter can take an Object, Boolean, String, or number as a parameter.

Return type: It returns a SchemaType Object as a response.

Creating node application And Installing Mongoose:

1. You can install this package by using this command.

npm install mongoose

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

npm version mongoose

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

node index.js

Project Structure: The project structure will look like this:

 

Example 1: 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

Javascript




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
            { 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 you have installed the mongoose module.

npm install mongoose

2. Run the code with the following command:

node index.js

Output:

 

Example 2: 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

Javascript




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
            { 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:

 

Reference: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-index



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads