我有以下Mongoose模式:
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,
},
},
],
});
以及以下预挂接:
UserSchema.pre('save', function (next) {
const user = this;
if (!user.toObject().tokens[0].token) {
// do something
next();
} else {
// do something else
next();
}
});
问题是,即使
tokens
属性完全为空,第一个案例(执行某些操作)不运行。我在这里做错什么了?