By default, each document in a Mongoose model has an _id field, which is typically automatically generated as a MongoDB ObjectId. A MongoDB ObjectId is a 12-byte field that typically contains a timestamp, a random value, and an increment counter to ensure the uniqueness of each _id.
However, there may be specific requirements where you need to set _id to a specific value or use different data types (such as strings or numbers). In Mongoose, you can customize the type and value of _id when defining the Schema.
Here is an example of how to customize _id in Mongoose:
javascriptconst mongoose = require('mongoose'); const Schema = mongoose.Schema; // Define a new Schema where the _id field is explicitly set to String type const customIdSchema = new Schema({ _id: { type: String, required: true }, name: String, age: Number }); // Create the model const User = mongoose.model('User', customIdSchema); // Create a new document instance with a custom _id const newUser = new User({ _id: 'custom-id-12345', name: 'Zhang San', age: 30 }); // Save to the database newUser.save() .then(doc => { console.log('Document saved successfully', doc); }) .catch(err => { console.error('Error saving document', err); });
In this example, we define a User model with _id explicitly set to String type. When creating the newUser instance, we manually specify _id as 'custom-id-12345'. This ensures that MongoDB uses the custom ID instead of generating a default ObjectId.
This approach allows you to customize the ID based on business needs, such as using a user's email address or other business identifiers as the document's unique identifier. However, when manually setting _id, you must ensure its uniqueness to avoid errors from duplicate _id values.