猫鼬唯一的电子邮件地址验证

时间:2019-11-17 06:23:40

标签: node.js mongoose nestjs

我正在尝试在用户注册时强制使用“唯一电子邮件地址”。但是猫鼬似乎并没有遵循我的架构中的unique: true标志。

// NPM Packages
import * as mongoose from 'mongoose';
import * as bcrypt from 'bcrypt';

export const UserSchema = new mongoose.Schema(
  {
    firstName: {
      type: String,
      trim: true,
      required: [true, 'Please enter First Name'],
    },
    lastName: {
      type: String,
      trim: true,
      required: [true, 'Please enter Last Name'],
    },
    email: {
      type: String,
      match: [
        /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
        'Please add a valid email address.',
      ],
      required: [true, 'Please enter Email Address'],
      unique: true,
      lowercase: true,
    },
    password: {
      type: String,
      required: [true, 'Please enter a password'],
      minlength: [6, 'Password must be at least 6 characters'],
      select: false,
    },
  },
  { timestamps: true },
);

// Encrypt User Password
UserSchema.pre('save', async function(next) {
  const salt = await bcrypt.genSalt(10); // Recommended in bcryptjs doc
  this.password = await bcrypt.hash(this.password, salt);
});

1 个答案:

答案 0 :(得分:1)

在诸如以下的模式中使用dropDups

email: {
  type: String,
  match: [
    /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\. 
 [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
    'Please add a valid email address.',
  ],
  required: [true, 'Please enter Email Address'],
  unique: true,
  lowercase: true,
  dropDups: true
}