1

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?

Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80
  • if `tokens` is completely empty, you would receive `Uncaught TypeError: Cannot read property 'token' of undefined` (try running this in the console: `[][0].token`) – nem035 Jul 14 '18 at 15:00
  • That error is never raised for some reason, do I need to add an additional logger or something to catch it? – Colin Ricardo Jul 14 '18 at 15:01

1 Answers1

0

You need to change your if in the pre hook method:

UserSchema.pre('save', function (next) {
  const user = this;

  if (user.toObject().tokens && user.toObject().tokens.length > 0) {
    console.log('do something');
    next();
  } else {
    console.log(' do something else');
    next();
  }
});

There are a lot of ways for validate a array, here one link with some options: Check is Array Null or Empty