I have the following Mongoose Schema:
const UserSchema = new Schema({
email: {
type: String,
minlength: 1,
required: true,
trim: true,
unique: true,
validate: {
validator: isEmail,
message: '{VALUE} is not a valid email.',
},
},
emailPhrase: {
type: String,
},
tokens: [
{
access: {
type: String,
required: true,
},
token: {
type: String,
required: true,
},
},
],
});
And the following pre-hook:
UserSchema.pre('save', function (next) {
const user = this;
if (!user.toObject().tokens[0].token) {
// do something
next();
} else {
// do something else
next();
}
});
The issue is, even when the tokens
property is completely empty, the first case (do something) doesn't run. What am I doing wrong here?