Search code examples
node.jsmongooseduplicateshookpre

Where to handle duplicate in mongoose


I am trying to figure out where is the best place to handle duplicates before inserting in 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);
    }
});

The probleme is that when I want to update the username for example.

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;
    }
}

This fires the pre hook and throws email already exists error. I think im handling this in the wrong place... Thank you!


Solution

  • const UserSchema = new Schema({
        username: {type:String,unique:true}
        email: String,
        password: String, });
    
    you can use unique:true while writing schema
    

    Hope this may help you