Home > Enterprise >  Mongoose validation
Mongoose validation

Time:05-30

when I create a user in mongoose and I don't give my email, I get an error, but if I don't provide the password, nothing shows up and the user is saved to the database. in both cases I use: required: [true, "error "]

image

CodePudding user response:

Have you tried adding minlength? Maybe trim would help? https://mongoosejs.com/docs/schematypes.html#string-validators

email: {
    type: String,
    required: [true, 'Please provide an email.'],
    minlength: 1,
    maxlength: 25,
    trim: true,
    unique: true,
},

CodePudding user response:

did you add validation for the password field? I do my user model like this:

const UserSchema = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  gender: {
    type: String,
    enum: ['male', 'female'],
  },
  profilePicture: {
    type: String
  },
  password: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
  },
}, {
  timestamps: true
}, );


// hash the password before the user is saved
UserSchema.pre('save', function hashPassword(next) {
  // hash the password only if the password has been changed or user is new
  if (!this.isModified('password')) {
    next();
    return;
  }

  // generate the hash
  _hash(this.password, null, null, (err, hash) => {
    if (err) {
      next(err);
      return;
    }

    // change the password to the hashed version
    this.password = hash;
    next();
  });
});

// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function comparePassword(password) {
  const data = compareSync(password, this.password);
  return data;
};

I hope this helps :)

  • Related