Block Save Repeated Data

Asked

Viewed 896 times

3

As I check in the controller, if there is already an email registered in the bank Mongoose and so, lock save it again?

  • Look I don’t know if it helps you 'cause I don’t have much experience with NodeJs .But try to make a query by sending the email with parameter if it returns something other than null you do the action of blocking the button

  • I also have no experience with Nodejs and Mongo, but it would not have something like UNIQUE on Mongo and that we managed to set up for the email field?

2 answers

2

The best way to do this is to establish a unique index in the field. This can be done by adding unique: true for setting the field in the schema:

var UserSchema = new mongoose.Schema({
  email: { type: String, unique: true }
  // ...
});

You can read about this Feature here: http://mongoosejs.com/docs/api.html#schematype_SchemaType-Unique

And about unique indexes in Mongodb here: http://docs.mongodb.org/master/core/index-unique/

Birds and updates will fail without further changes to your code when duplicate values are entered. Vitor’s response is valid, but liable to race conditions (and if a user with duplicate email is inserted between the find and the save?).

You can then treat the error that Mongodb will return in duplicate values:

// Ou dê match no código do erro (E11000)
if(_.contains(err.message, 'duplicate key error') &&
   _.contains(err.message, 'users.$email')) {
  err = new Error('This email is already registered');
  err.status = 400;
}

throw err;

1

You can make a validator which only allows the inclusion or alteration of a user if the email address does not exist in the collection:

UserSchema.path('email').validate(function (email, done) {
    var User = mongoose.model('User')

    // Check only when it is a new user or when email field is modified
    if (this.isNew || this.isModified('email')) {
        User.find({ email: email }).exec(function (err, users) {
            done(!err && users.length === 0)
        })
    } else done(true);
}, 'Email já registrado.');

In the controller check error after trying to save user:

/* Create new user. */
exports.new = function(req, res) {
  var user = new User(req.body);
  user.save(function(err){
    if (err & err.errors.email) 
      return res.status(400).json({message: err.errors.email.type});
    else 
      return res.sendStatus(201);
    }
  });
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.