代码之家  ›  专栏  ›  技术社区  ›  Colin Ricardo

Mongoose对象

  •  0
  • Colin Ricardo  · 技术社区  · 7 年前

    我有以下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 属性完全为空,第一个案例(执行某些操作)不运行。我在这里做错什么了?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Marcus Vinicius Sousa Vieira    7 年前

    您需要在预挂接方法中更改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

    推荐文章