title: Mongoose: How to prevent mongodb to save duplicate email records in database
body: <p>I want to make the key email unique across that collection but i cant getting this working, here is my server code.</p>
  
  <pre><code>// Create a schema
  var userSchema = new mongoose.Schema({
      email: { type: String, required: true},
      password: String
  });
  
  var userModel = mongoose.model("user", userSchema);
  
  router.post('/postuser', (req, res) =&gt; {
      console.log('Requested data to server: ' + JSON.stringify(req.body._user));
  var user = new userModel({
      email: req.body._user.email,
      password: req.body._user.password
  });
  // user.isNew = false;
  user.save((err, data) =&gt; {
      console.log('Analyzing Data...');
      if(data) {
          console.log('Your data has been successfully saved.');
          res.json(data);
  }
  else {
    console.log('Something went wrong while saving data.');
    console.log(err);
    res.send(err);
  }
  
  })
  });
  </code></pre>
  
  <p>Note: I also try <code>email: { type: String, required: true, unique: true}</code> but its not working and show below error.</p>
  
  <blockquote>
    <p>name: 'MongoError',</p>
    
    <p>message: 'E11000 duplicate key error collection: hutreservationsystem.users</p>
    
    <p>index: _Email_1 dup key: { : null }',</p>
    
    <p>driver: true,</p>
    
    <p>code: 11000,</p>
    
    <p>index: 0,</p>
    
    <p>errmsg: 'E11000 duplicate key error collection: hutreservationsystem.users index: _Email_1 dup key: { : null }',</p>
    
    <p>getOperation: [Function],</p>
    
    <p>toJSON: [Function],</p>
    
    <p>toString: [Function] }</p>
  </blockquote>