2016-10-06 54 views
0

我想弄清楚插入貓鼬之前處理重複的最佳位置在哪裏。在哪裏處理貓鼬

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

這會引發預鉤並拋出電子郵件已存在的錯誤。 我想即時處理這個錯誤的地方...謝謝!

回答

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

you can use unique:true while writing schema 

希望這可以幫助你

+0

謝謝,我嘗試過這樣做,但我沒有任何錯誤,但我現在擁有它。謝謝! –

0

模式級validations

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