![]() |
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:
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
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
Steps to run the code: Run the following command: node index.js Output: ![]()
Reference: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-index |
Reffered: https://www.geeksforgeeks.org
Node.js |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |