Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return only specific attributes when using Sequelize Create method

I have been searching through Sequelize documentation and forums for the correct syntax and it seems I am doing it the right way, but for some reason the password field is still being returned in the response payload...

The following link shows the attributes exclude syntax I am using was added in version 3.11 of Sequelize: https://github.com/sequelize/sequelize/issues/4074

Anyone know what I might be missing here? Below is the Create method and the console log from the Insert statement.

Create method

async create(req, res) {
try {
    let user = await User.create({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
        password: req.body.password
    }, {
        attributes: {
            exclude: ['password']
        }
    });

    console.log("USER: ", user);

    res.status(201).send(user.toJSON());
}
catch (error) {
    res.status(500).send(error)
};

}

Console Log

Executing (default): INSERT INTO "Users" ("id","firstName","lastName","email","password","createdAt","updatedAt") VALUES (DEFAULT,'James','Martineau','[email protected]','$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2','2019-02-28 15:18:15.856 +00:00','2019-02-28 15:18:15.856 +00:00') RETURNING *;

USER: User { dataValues: { id: 6, firstName: 'James', lastName: 'Martineau', email: '[email protected]', password: '$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2', updatedAt: 2019-02-28T15:18:15.856Z, createdAt: 2019-02-28T15:18:15.856Z }...

like image 964
James Avatar asked Feb 28 '19 15:02

James


3 Answers

The proper way to handle this is to leverage the afterCreate and afterUpdate hooks on the actual data model, that Sequelize exposes. These hooks are fired after the record is persisted, so any mutations to the dataValues will only be reflected in the return.

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;
            },
        }
    }
);

Here is a link to the documentation: https://sequelize.org/master/manual/hooks.html

like image 114
Joe Avatar answered Oct 23 '22 03:10

Joe


I see in the document, you can't exclude attributes when you create a model. Only exclude when you find a model.

I suggest:

async create(req, res);
{
    try {
        let user = await User.create({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email: req.body.email,
            password: req.body.password
        });
        delete user["password"];//delete field password
        console.log("USER: ", user);

        res.status(201).send(user.toJSON());
    }
    catch (error) {
        res.status(500).send(error);
    };
}
like image 3
Chuong Tran Avatar answered Oct 23 '22 03:10

Chuong Tran


Try overloading Sequelize Model class with your desired functionality. For example, run following code once during application bootstrap:

import {Model} from 'sequelize';

const toJSON = Model.prototype.toJSON;

Model.prototype.toJSON = function ({attributes = []} = {}) {
    const obj = toJSON.call(this);

    if (!attributes.length) {
      return obj;
    }

    return attributes.reduce((result, attribute) => {
      result[attribute] = obj[attribute];

      return result;
    }, {});
  };

After that, you can use your code as usual, but with an attributes option:

User.toJSON({attributes: ['name', 'etc...']}).

like image 2
Andrej Burcev Avatar answered Oct 23 '22 05:10

Andrej Burcev