【问题标题】:Mongoose Unique Email Address ValidationMongoose 唯一电子邮件地址验证
【发布时间】:2020-03-12 20:22:24
【问题描述】:

我正在尝试在用户注册时强制使用唯一电子邮件地址。但是 Mongoose 似乎没有遵守我架构中的 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);
});

【问题讨论】:

  • 添加unique 就像添加index。尝试重新启动 mongo 服务器并再次尝试插入。
  • @Himakar 所以使用独特的不会实时工作?
  • 当您添加 createIndex、unique 等时,您必须重新启动以反映更改。

标签: node.js mongoose nestjs


【解决方案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
}

【讨论】:

  • dropDups 有什么用? @Avid Programmer 你能详细说明一下吗?
猜你喜欢
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 2014-03-02
  • 2015-01-03
  • 2014-06-12
  • 1970-01-01
相关资源
最近更新 更多