First, MongoDB's default ObjectId is a 12-byte BSON type that ensures uniqueness of documents within a collection. However, in certain scenarios, developers might prefer using UUID (Universal Unique Identifier), a 16-byte identifier that provides broader uniqueness and is suitable for sharing data across multiple databases or services.
In Mongoose, to use UUID as the ObjectId, we can follow the steps and code implementation below:
Step 1: Install and import the required dependencies
First, ensure that the uuid library is installed for generating UUIDs.
bashnpm install uuid
Step 2: Define the Schema
In the Mongoose model definition, we can use UUID by setting the type to Buffer and specifying the subtype as 4 for UUID.
javascriptconst mongoose = require('mongoose'); const { v4: uuidv4 } = require('uuid'); const userSchema = new mongoose.Schema({ _id: { type: Buffer, subtype: 4, default: uuidv4 }, name: String, email: String }); // Set the default value of _id to the generated UUIDv4 userSchema.set('toObject', { getters: true }); userSchema.set('toJSON', { getters: true }); const User = mongoose.model('User', userSchema); module.exports = User;
Here, we use the v4 method from the uuid library to generate UUIDs. We need to ensure that the _id field is correctly displayed as a string when outputting (e.g., when converting to JSON or Object). Therefore, we configure the Schema with toObject and toJSON settings.
Step 3: Use the Model
Now, when creating a new user document, Mongoose automatically generates a UUID for us.
javascriptconst newUser = new User({ name: '张三', email: 'zhangsan@example.com' }); newUser.save().then(() => { console.log('User saved successfully'); }).catch(error => { console.error('Error saving user:', error); });
By doing this, we can ensure that each user has a globally unique identifier, which is very useful when handling data across databases or systems.
In summary, while MongoDB's default ObjectId is sufficient for most uniqueness requirements, using UUID provides a safer option in globally distributed systems. Implementing it in Mongoose is relatively straightforward, primarily involving appropriate type settings and default value configurations in the Schema definition.