在哪里处理猫鼬中的重复项

Where to handle duplicate in mongoose

我想找出在插入 mongoose 之前处理重复项的最佳位置。

const UserSchema = new Schema({
    username: String,
    email: String,
    password: String,
});

const User = mongoose.model('User', UserSchema);

UserSchema.pre('save', async function (next) {
    try {
        const doc = await User.findOne({ email: this.email }).exec();
        if (doc) {
            throw new Error('Email already used');
        }
        next();
    } catch (err) {
        next(err);
    }
});

问题是当我想更新用户名时。

async function updateUsername(id, username) {
    try {
        const doc = await User.findOne({ _id: id }).exec();
        if (docs) {
            doc.username = username;
            await docs.save();
        } else {
            throw {
                msg: 'Does not exist'
            };
        }

    } catch (err) {
        throw err;
    }
}

这会触发预挂钩并抛出电子邮件已存在错误。 我认为我在错误的地方处理这个...谢谢!

const UserSchema = new Schema({
    username: {type:String,unique:true}
    email: String,
    password: String, });

you can use unique:true while writing schema

希望对您有所帮助

架构级别 validations

  const UserSchema = new Schema({
        username: String,
        email:  {type:String,unique:true},
        password: String,
    });