Reputation: 8297
I am implementing an API for a task management and has two endpoints users and tasks. The schema design for the 'users' looks like:
// Define our user schema
var userSchema = new mongoose.Schema({
name: {
type:String,
required: true
},
email: {
type: String,
required: true
},
pendingTasks: [String],
dateCreated: {
type: Date,
default: Date.now }
});
My question is, how can I make the email for each data to be unique? (Not allowing multiple users with the same email)
Upvotes: 0
Views: 38
Reputation: 3020
From my understanding, you do not allow duplicate emails in your Collection, right?
One way to archive this is to add a unique index
definition to the email
property. Like this:
// Define our user schema
var userSchema = new mongoose.Schema({
name: {
type:String,
required: true
},
email: {
type: String,
required: true,
index: true, // NEW Added!
unique: true // NEW Added!
},
pendingTasks: [String],
dateCreated: {
type: Date,
default: Date.now }
});
Pls remember to restart your mongoose(I think you can do it by restart Node.js application). By default, mongoose will create the index when it starts up.
If you want to confirm the index to be created, login to the mongodb console and use: db.users.getIndexes()
to check.
Upvotes: 1