본문 바로가기

nodejs

[Node.js] Sequelize Create 메서드에서 특정 레코드만 반환

Sequelize에서 Create 메서드 사용 시 전체 레코드 반환이 아니라 필요한 레코드만 반환이 필요할 때 아래 코드처럼에서 모델 정의에서 hooks 옵션을 추가해준다.

sequelize.define(
    'User',
    {
        id: { type: DataType.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true },
        username: { type: DataType.STRING, allowNull: false },
        password: { type: DataType.STRING, allowNull: false }
    },
    {
        hooks: {
            afterCreate: (record) => {
                delete record.dataValues.password;
            },
            afterUpdate: (record) => {
                delete record.dataValues.password;
            },
        }
    }
);

 

 

참고

 출처: https://sequelize.org/master/manual/hooks.html

 

Manual | Sequelize

Hooks Hooks (also known as lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you want to always set a value on a model before saving it, you can add a beforeUpdate hook. Note: You can't use

sequelize.org

 출처:  https://stackoverflow.com/questions/54929244/how-to-return-only-specific-attributes-when-using-sequelize-create-method