Mongoose Schemas Indexes
Last Updated :
20 Jan, 2023
Mongoose is a MongoDB object modeling and handling for a node.js environment. When a document is produced, Mongoose automatically uses the _id property to index all of the models. We can use Mongoose to define the path-level indexes in our schema. For each defined index in the schema, Mongoose automatically runs createIndex when the application first launches.
Creating node application and Installing Mongoose:
Step 1: Create a node application using the following command:
mkdir folder_name
cd folder_name
npm init -y
Step 2: Install the required module using the following command:
npm install mongoose
Project Structure: It will look like the following.
Example 1: In this example, we will create some documents and see the default indexes, which is set by the mongoose automatically.
Javascript
const mongoose = require( 'mongoose' );
mongoose.connect(url)
.then((ans) => {
console.log( "Connected successfully" )
})
. catch ((err) => {
console.log( "Error in the Connection" )
})
const Schema = mongoose.Schema;
const collection_structure = new Schema({
name: String,
marks: Number,
})
const collections = mongoose.model( "GFG" , collection_structure)
collections.create({
name: `Ragavpp`,
marks: 13,
})
.then((ans) => {
console.log( "Document inserted" )
})
. catch ((err) => {
console.log(err.Message);
})
|
Step to Run Application: Run the application using the following command from the root directory of the project:
node script.js
Output:
Connected Successful
Document inserted
Following we can see the default indexes in Atlas GUI:
indexes output
Example 2: In this example, we will create indexes with mobile_No.
Javascript
const mongoose = require( 'mongoose' );
mongoose.set( 'strictQuery' , false );
mongoose.connect(url)
.then((ans) => {
console.log( "Connected Successful" )
})
. catch ((err) => {
console.log( "Error in the Connection" )
})
const Schema = mongoose.Schema;
const collection_structure = new Schema({
name: {
type: String,
require: true ,
},
marks: {
type: Number,
default : 0
},
mobile: {
type: Number,
index: true ,
require: true ,
}
})
const collections = mongoose.model( "GFG" , collection_structure)
collections.create({
name: `Sam Snehil`,
marks: 88,
mobile: 9338948473,
})
.then((ans) => {
console.log( "Document inserted" )
})
. catch ((err) => {
console.log(err);
})
|
Step to Run Application: Run the application using the following command from the root directory of the project:
node script2.js
Step to Run Application: Run the application using the following command from the root directory of the project:
node main.js
Output:
Following we can see the mobile in indexes on Atlas GUI:
index output2
Reference: https://mongoosejs.com/docs/guide.html#indexes
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...