hello guys,
I have UserSchema that has 3 fields right now (email, password, username) . I want Username not to be required:true, and Username.value equals to email.value by default. Help me please who knows how to solve this.
Or maybe it will be better to create separate schema Email for both fields??
1 Like
Hi @Oleg_Khalanskii,
You can do this with pre middleware. You can do it like this:
const UserSchema = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
username: { type: String }
});
UserSchema.pre('save', (next) => {
this.username = this.get('email');
next();
});
You can read more here: Mongoose v6.9.1: Middleware.
1 Like
