2016-10-06 5 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

は、私が前にこれをやってみましたが、私はすべてのエラーを持っていますが、今それを持っイムdidntは、ありがとうございます。ありがとう! –

0

スキーマレベルvalidationsを助けるかもしれない希望は

const UserSchema = new Schema({ 
     username: String, 
     email: {type:String,unique:true}, 
     password: String, 
    }); 
関連する問題