简体   繁体   中英

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','test@gmail.com','$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: 'test@gmail.com', password: '$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2', updatedAt: 2019-02-28T15:18:15.856Z, createdAt: 2019-02-28T15:18:15.856Z }...

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

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

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...']}) .

With a quick read through the docs, it seems attributes is only mentioned within queries like:

Model.findAll({
  attributes: { exclude: ['baz'] }
});

( http://docs.sequelizejs.com/manual/tutorial/querying.html#attributes )

If you want to exclude password with create , you could do something like:

let user = await User.create({
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    email: req.body.email,
    password: req.body.password
}, {
    fields: ['firstName', 'lastName', 'email']
});

( http://docs.sequelizejs.com/manual/tutorial/instances.html#creating-persistent-instances )

 User.create(req.body).then(user => { delete user.dataValues.password res.json(user) }).catch(error => { // do something with error })

I know it's an old question, but it's a problem i faced recently. The way I solved this, is like this:

try {
    const { firstName, lastName, email } = await User.create({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
        password: req.body.password
    })
    const user = { firstName, lastName, email }

}

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

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

You can instantiate the fields you want like this, at least it's what i'm doing everywhere in my code

hope this works for you too :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM