mongoose를 사용할때는 아래처럼 다양한 메소드를 사용했다
UserSchema.pre("save", function (next) {
...
});
UserSchema.methods.checkPassword = function (userPassword, next) {
...
};
이전 작업을 마이그레이션하는 중
이걸 어떻게 sequelize에 맞게 변환할 수 있는지 생각해봤다
그리고 알게된 sequelize hook
사용법은 mongoose와 비슷하게 모델의 클래스에 지정해주면 된다
class User extends Model {}
User.init({
username: DataTypes.STRING,
mood: {
type: DataTypes.ENUM,
values: ['happy', 'sad', 'neutral']
}
}, {
hooks: {
beforeValidate: (user, options) => {
user.mood = 'happy';
},
afterValidate: (user, options) => {
user.username = 'Toni';
}
},
sequelize
});
// Method 2 via the .addHook() method
User.addHook('beforeValidate', (user, options) => {
user.mood = 'happy';
});
User.addHook('afterValidate', 'someCustomName', (user, options) => {
return Promise.reject(new Error("I'm afraid I can't let you do that!"));
});
커스텀으로 만들고 싶으면 prototype로 모델에 추가하면 된다.
Users.prototype.checkPassword = async function (userPassword) {
...
};