【发布时间】: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 等时,您必须重新启动以反映更改。