Mongoose Enum Field Not Enforcing Values
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please tell us your name!']
},
email: {
type: String,
required: [true, 'Please provide your email'],
unique: true,
lowercase: true,
validate: [validator.isEmail, 'Please provide a valid email']
},
photo: String,
role: {
type: String,
enum: ['user', 'guide', 'lead-guide', 'admin'],
default: 'user'
},
password: {
type: String,
required: [true, 'Please provide a password'],
minlength: 8,
select: false
},
passwordConfirm: {
type: String,
required: [true, 'Please confirm your password'],
validate: {
// This only works on CREATE and SAVE!!!
validator: function(el) {
return el === this.password;
},
message: 'Passwords are not the same!'
}
},
passwordChangedAt: Date,
passwordResetToken: String,
passwordResetExpires: Date,
active: {
type: Boolean,
default: true,
select: false
}
});
This is my userShema. When I try to save a new user without providing a role, it works as a default value "user". But when I save the user with "admin" role, it doesn’t work and always return a role as a "user".
api call
exports.signup = catchAsync(async(req, res, next) => {
const newUser = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm
});
const token = signToken(newUser._id);
res.status(201).json({
status: 'success',
token,
data: {
user: newUser
}
})});
this is my signup function
>Solution :
You are not declaring role in your Model.create() function so it will always default to the deafult value of user.
You can try just using optional chaining so if role is part of the post request it will use it, otherwise it will use the default like so:
const newUser = await User.create({
role: req.body?.role || 'user'
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm
});
You will still get validation because if the req.body.admin value is not part of the enum array mongoose will throw a validation error.