猫鼬到对象

时间:2018-07-14 14:39:47

标签: node.js mongodb mongoose

我有以下猫鼬模式:

module: {
  mode: process.env.NODE_ENV // production or development
}

以及以下预钩:

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(); } }); 属性完全为空,第一种情况(执行某些操作)也不会运行。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要使用pre hook方法更改if:

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();
  }
});

有很多验证数组的方法,这里有一些选项的链接:   Check is Array Null or Empty