0

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)

Dawn17
  • 7,825
  • 16
  • 57
  • 118
  • 1
    Maybe by l[ooking at the documentation and searching "unique"?](http://mongoosejs.com/docs/validation.html#the-unique-option-is-not-a-validator). A simple search for ["mongoose unique"](https://www.google.com/q=mongoose+schema+unique) or ["mongodb unique"](https://www.google.com/q=mongodb+unique) also leads you to loads of relevant information. – Neil Lunn Nov 02 '17 at 03:31

1 Answers1

1

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/
yellowB
  • 2,900
  • 1
  • 16
  • 19
  • Thanks this is a great answer. Would you also be able to take a look at my different question about creating a RESTful API ? : https://stackoverflow.com/questions/47067974/validator-erorr-when-posting-creating-a-restful-api – Dawn17 Nov 02 '17 at 05:08
  • @Dawn17, you're welcome, you can see my suggestion on that question :) – yellowB Nov 02 '17 at 05:23