0

I have a Schema

    var UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    trim: true,
    minlength: 1,
    unique: true,
    validate: {
      validator: validator.isEmail,
      message: "{VALUE} is not a valid email"
     }
   }
}

And as you see, email has property "unique". However, when I create a multiple users with the same email there is no errors popping anywhere. So, I decided to create a loop, in "PRE" method. Before I save new user, it checks if the email already exist in mongo then deletes it

    UserSchema.pre('save', function (next) {
      var user = this;

      User.find({email: user.email}).then((res) => {
        return User.remove({email: res[1].email});
     }).then((res) => {
      console.log(res);
      next()
    });


    });

But it deletes every user in collection, even the unique one created before. Can anybody give an advice or tell possible ways of fixing it? Any help appreciated. Maybe there is another way to check email "uniqueness"?

Drews
  • 5
  • 1
  • Likely dupe of https://stackoverflow.com/questions/30966146/mongoose-schema-unique-not-being-respected – JohnnyHK Apr 30 '18 at 16:58

1 Answers1

0

Try This ...

UserSchema.pre('save', function (next) {
          var user = this;

          User.findOne({email: user.email}).then((res) => {
            return User.remove({email: res.email});
         }).then((res) => {
          console.log(res);
          next()
        });
       });
Ahmed Kesha
  • 810
  • 5
  • 11