Sequelize: Don't return password on Create

纵然是瞬间 提交于 2019-12-11 01:58:19

问题


When I create a new instance of my User with Sequelize, I get the full object returned from the database as a response to the Create. I'm trying to prevent Sequelize from returning the hashed password stored in my User table on create.

exports.create = (payload, err, success) => {
  db.user.create(payload).then(success).catch(err);
  console.log('Created new user record.');
};

I tried using the exclude property, but the full object returns.

exports.create = (payload, err, success) => {
  db.user.create(payload, {
    attributes: {
      exclude: ['password']
    }
  }).then(success).catch(err);
  console.log('Created new user record.');
};

I am able to use the exclude property in attributes on my find and findAll routes like the example below, but I haven't been able to get it to work with my create.

exports.find = (payload, err, success) => {
  db.user.find({
    where: {
     id: payload.id,
    },
    attributes: {
      exclude: ['password']
    }
  }).then(success).catch(err);
  console.log('Retrieved user record with id: ' + payload.id);
};

回答1:


You can try using toJSON instance method to exclude attributes:

Model:

instanceMethods: {
      toJSON: function () {
          const userObj = Object.assign({}, this.dataValues);

          delete userObj.password;

          return userObj
      }
}

Route file:

user.create(request.body, (err) => {
  res.status(500).json(err);
  console.log('Error creating new user.');
}, (data) => {
  res.status(200).json(data.toJSON());
  console.log('User created.'); 
});


来源:https://stackoverflow.com/questions/45655612/sequelize-dont-return-password-on-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!