CCCC
CCCC

Reputation: 6461

Express js - how to remove certain field from response

In my current login api, it returns

"user": {
        "id": "3e85decc-2af4-436c-8b7f-e276771234f5",
        "email": "[email protected]",
        "password": "$xxxxxxxxxx",
        "createdAt": "2021-05-14T08:48:31.000Z",
        "updatedAt": "2021-05-14T08:48:31.000Z"
    },
    "token": "xxxxx"
}

I want to remove the password field in my response, so I use delete user.password in my code, but it's not working

/api/users.js

router.post('/login', (req, res, next) => {
  passport.authenticate('local', {session: false}, (err, user, info) =>{
    if (err || !user) {...}
    req.login(user, {session: false}, (err) => {
      if (err) {
          res.send(err);
      }
      const token = jwt.sign(user, 'your_jwt_secret');
      console.log(user) // show dataValues and _previousDataValues instead of normal JSON object
      delete user.password // not working
      return res.json({user, token});
   });
  })(req, res);
});

I tried to log user object for above file, it returns:

users {

dataValues: {

id: '3e85decc-2af4-436c-8b7f-e276771234f5',

email: '[email protected]',

password: '$xxxxxxxxxx',

createdAt: 2021-05-14T08:48:31.000Z,

updatedAt: 2021-05-14T08:48:31.000Z

},

_previousDataValues: {

id: '3e85decc-2af4-436c-8b7f-e276771234f5',

email: '[email protected]',

password: '$xxxxxxxxxx',

createdAt: 2021-05-14T08:48:31.000Z,

updatedAt: 2021-05-14T08:48:31.000Z

},

_changed: Set(0) {},

_options: {

isNewRecord: false,

_schema: null,

_schemaDelimiter: '',

raw: true,

attributes: [ 'id', 'email', 'password', 'createdAt', 'updatedAt' ]

},

isNewRecord: false

}

This is my user model. I am using Sequelize.

const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
const db = require('../sequelize')

let users = db.define('users', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      allowNull: false,
      primaryKey: true
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'email'
    },
    password: {
      type: DataTypes.STRING,
    },
  },
  {
    hooks: {
      beforeCount(options) {
        options.raw = false;
      }
    }
  }
);
  
module.exports = users;

Upvotes: 2

Views: 1854

Answers (4)

CCCC
CCCC

Reputation: 6461

Finally solved it using user.get({plain: true})

      let plainUser = user.get({plain: true})
      delete plainUser['password']
      return res.json({user, token});

Upvotes: 1

Ashok Kumar
Ashok Kumar

Reputation: 326

Try below code in your model to override the sequelize toJSON function

const User = db.define('users', {
    id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        allowNull: false,
        primaryKey: true
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'email'
    },
    password: {
        type: DataTypes.STRING,
    },
},
    {
        hooks: {
            beforeCount(options) {
                options.raw = false;
            }
        }
    }
);

User.prototype.toJSON = function () {
 const values = Object.assign({}, this.get());

 delete values.password;
 return values;
};

or using omit() withlodash for cleaner code

User.prototype.toJSON = function () {
const values = {
    ..._.omit(this.get(), ['password'])
};

return values;
};

Upvotes: 0

lets code
lets code

Reputation: 143

why dont you re-create your result response, something like this:

let response = {
     "user": {
         "id": user.dataValues.id,
         "email": user.dataValues.email,
         "createdAt": user.dataValues.createdAt,
         "updatedAt": user.dataValues.updatedAt
     },
     "token": "xxxxx"
 }
JSON.stringify(response)

Upvotes: 0

David Jones
David Jones

Reputation: 3382

It's probably not a good idea to delete properties from the Model directly. Try using ToJSON() to convert the Model to a plain Javascript object and delete the password from that.

plainUser = user.ToJSON();
delete plainUser.password

Upvotes: 0

Related Questions