In MongoDB and Mongoose, by default, each model includes an _id field as the primary key for uniquely identifying documents.
However, in certain scenarios, we may need to define another field as the primary key instead of _id.
Although MongoDB itself does not support modifying the behavior of the default _id field, we can treat other fields as primary keys by implementing a unique index.
Within Mongoose, to define a field as the primary key, set its unique property to true. This ensures that the field's values are unique within the collection, effectively mimicking primary key functionality.
Here is an example of setting a field other than _id as a unique key in a Mongoose model:
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ username: { type: String, unique: true, // Set username as a unique index required: true }, email: { type: String, unique: true, // Set email as a unique index required: true }, password: { type: String, required: true } }); const User = mongoose.model('User', userSchema); // Create a new document instance const newUser = new User({ username: 'john_doe', email: 'john.doe@example.com', password: '123456' }); newUser.save() .then(doc => console.log('User saved:', doc)) .catch(err => console.error('Error saving user:', err));
In this example, we define a User model where the username and email fields are set as unique indexes. Consequently, in the User collection, duplicate username or email values are prevented, allowing these fields to serve a similar role to _id in uniquely identifying documents.
Note that while multiple fields can be set as unique indexes, the _id field remains present in the database and continues to function as the default primary key for MongoDB documents.