title: Unique Fields in Mongoose
body: <p>I'm trying to enforce uniqueness by field on a mongoose model, in an existing database.</p>
  
  <pre><code>const UserSchema = new mongoose.Schema({
    email: {
      type: String,
      required: true,
      unique: true,
    }
  })
  </code></pre>
  
  <p>Then when I create a user with an email that is already assigned, it passes, and I have 2 users with the same email.</p>
  
  <p>I have read all related SO answers > 2015 and all about <code>dropDups</code>, <a href="https://docs.mongodb.com/v3.2/release-notes/3.0-compatibility/#indexes" rel="nofollow noreferrer">which is deprecated</a>. </p>
  
  <p>I think I fixed this issue by manually running</p>
  
  <pre><code>db.users.createIndex({email:1}, {unique:true})
  </code></pre>
  
  <p>However this obviously becomes cumbersome both in development and in production, especially considering the <a href="http://mongoosejs.com/docs/schematypes.html" rel="nofollow noreferrer">mongoose docs</a> state that the attribute takes care of it:</p>
  
  <blockquote>
    <p>unique: boolean, whether to define a unique index on this property.</p>
  </blockquote>
  
  <p>Can someone provide a clear solution to enforcing uniqueness by field on a Mongoose model, considering an existing database and a fresh collection? Thanks</p>