How to create an id using mongoose in Javascript?

Last Updated : 30 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose is a powerful tool that simplifies MongoDB operations by providing a structured way to define schemas and models. With Mongoose, developers can define relationships between data, apply validation rules, and create reusable query logic.

In this article, We will learn about Mongoose, Defining a Mongoose Schema and Default ID Generation in Mongoose, Custom ID Field in Mongoose Generating Custom IDs with Hooks and Using Plugins for ID Generation in detail.

Understanding Mongoose

Mongoose makes it easy to work with databases by providing a way to define models and schemas in a structured manner. It comes seamlessly with MongoDB, enabling one to work with MongoDB documents in a more efficient and organized manner. Through Mongoose, developers can create relationships between data, validate rules, and reusable query logic.

Mongoose offers a variety of features, including middleware hooks and for managing tricky tasks like data transformation and validation. Mongoose overall improves the experience of developing while using MongoDB in Node.js applications.

Defining a Mongoose Schema

Before creating IDs, we need to define a Mongoose schema. A schema represents the structure of documents within a collection. Here's an example of defining a simple schema.

// Import the mongoose library
const mongoose = require('mongoose');

// Define a new mongoose schema for the user
const userSchema = new mongoose.Schema({
name: String, // Define a field for the user's name of type String
email: String // Define a field for the user's email of type String
});

// Create a new mongoose model based on the schema
const User = mongoose.model('User', userSchema); // 'User' is the model name, and userSchema is the schema

Default ID Generation in Mongoose

Each document in a MongoDB collection requires a unique identifier, which MongoDB uses as the primary key. MongoDB uses ObjectId as the default unique identifier, which is a 12-byte value represented as a 24-character hexadecimal string.

ObjectId includes a timestamp, machine identifier, process identifier, and a random value. When we define a Mongoose schema without specifying an ID field, Mongoose automatically adds an _id field with a generated ObjectId value to our documents.

// Import the mongoose library
const mongoose = require('mongoose');

// Define a new mongoose schema for the model
const schema = new mongoose.Schema({
name: String, // Define a field for the name of type String
age: Number // Define a field for the age of type Number
});

// Create a new mongoose model based on the schema
const Model = mongoose.model('Model', schema); // 'Model' is the model name, and schema is the schema

// Create a new instance of the Model with name 'John' and age 30
const instance = new Model({ name: 'John', age: 30 });

// Log the newly created instance
console.log(instance); // { _id: 5c4830d4b55ae6b12b8b518c, name: 'John', age: 30 }

Custom ID Field in Mongoose

ObjectId is best for most situations, but there are some situations where custom IDs are to be used like sequential numbers or UUIDs for readability or to integrate with other systems. We can specify the _id field in our schema to define a custom ID field in Mongoose.

// Define a new mongoose schema for the custom model
const customSchema = new mongoose.Schema({
customId: String, // Define a field for the customId of type String
name: String, // Define a field for the name of type String
age: Number // Define a field for the age of type Number
});

// Create a new mongoose model based on the custom schema
const CustomModel = mongoose.model('CustomModel', customSchema); // 'CustomModel' is the model name, and customSchema is the schema

// Create a new instance of the CustomModel with customId '123abc', name 'Alice', and age 25
const customInstance = new CustomModel({ customId: '123abc', name: 'Alice', age: 25 });

// Log the newly created customInstance
console.log(customInstance); // { _id: '123abc', name: 'Alice', age: 25 }

Generating Custom IDs with Hooks

Mongoose provides pre and post hooks that allow us to run functions before or after performing operations such as saving or updating documents. Hooks can be useful to create custom IDs dynamically before saving documents into the database. By adding a pre('save') hook to your schema, we can make sure that the custom ID is created prior to saving the document.

// Define a pre-save hook on the customSchema to generate a customId if not already set
customSchema.pre('save', function(next) {
if (!this.customId) {
// Call the generateCustomId function to generate a custom ID
this.customId = generateCustomId();
}
next();
});

// Function to generate a custom ID
function generateCustomId() {
// Placeholder logic to generate a custom ID
return 'generatedID123'; // Return a hardcoded custom ID for demonstration purposes
}

Using Plugins for ID Generation

Mongoose allows us to create and reuse plugins to extend schema functionality. We can encapsulate ID generation logic within a plugin and apply it to multiple schemas across our application.

// Define a plugin called idGeneratorPlugin to add customId field and pre-save hook to the schema
const idGeneratorPlugin = function(schema, options) {
// Add a customId field to the schema
schema.add({ customId: String });

// Define a pre-save hook to generate a customId if not already set
schema.pre('save', function(next) {
if (!this.customId) {
// Call the generateCustomId function to generate a custom ID
this.customId = generateCustomId();
}
next();
});

// Function to generate a custom ID
function generateCustomId() {
// Placeholder logic to generate a custom ID
return 'generatedID123'; // Return a hardcoded custom ID for demonstration purposes
}
};

// Apply the idGeneratorPlugin to the customSchema
customSchema.plugin(idGeneratorPlugin);

By applying the idGeneratorPlugin to our schema, we can easily generate custom IDs for multiple models with minimal code duplication.

Conclusion

In this article, we have learn about various methods for generating custom IDs using Mongoose in JavaScript. From using default ObjectId to custom ID fields and ID generation logic with hooks and plugins, we have options spanning from one end to the other to cater to the needs of your application.

By learning these principles and best practices, you are well-equipped to handle unique identifiers in your MongoDB-backed applications, guaranteeing data integrity and consistency. As a beginner or seasoned developer, learning ID generation with Mongoose is an important skill for web development in today's web age.


Next Article
Article Tags :

Similar Reads