Dawn17
Dawn17

Reputation: 8297

Making a field in a schema design unique. (RESTful API)

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

Answers (1)

yellowB
yellowB

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.

Reference:

  1. How to define index by mongoose: http://mongoosejs.com/docs/schematypes.html
  2. Mongodb offical guide: https://docs.mongodb.com/manual/core/index-unique/

Upvotes: 1

Related Questions