In Mongoose, ObjectId is a data type of MongoDB used to uniquely identify documents. Mongoose leverages MongoDB's underlying bson library to generate ObjectId values.
When defining a field of type ObjectId in a Mongoose model, for example, in the user model definition:
jsconst mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ name: String, // Define ObjectId type field _id: Schema.Types.ObjectId }); const User = mongoose.model('User', userSchema);
When creating a new document and saving it to the database, Mongoose automatically generates a new ObjectId for the _id field. For example:
jsconst newUser = new User({ name: 'John Doe' }); newUser.save((err, savedUser) => { if (err) throw err; // savedUser._id will be a newly generated ObjectId console.log(savedUser._id); });
If you do not explicitly declare the _id field in your model definition, Mongoose will automatically add an _id field to each document and generate a new ObjectId.
ObjectId is a 12-byte value, typically composed of the following parts:
- 4-byte timestamp representing the creation time of the ObjectId.
- 5-byte random value to ensure uniqueness of ObjectId generated at the same time.
- 3-byte increment counter starting from the random value.
This structure ensures that generated ObjectId values remain unique and time-ordered even under heavy operations.
In certain cases, you may need to manually generate an ObjectId. You can achieve this using Mongoose's Types object:
jsconst { Types } = require('mongoose'); const objectId = new Types.ObjectId();
Now the objectId variable contains a newly generated ObjectId instance, which can be used wherever an ObjectId is required.