如何在使用 Sequelize Create 方法时仅 return 特定属性

How to return only specific attributes when using Sequelize Create method

我一直在 Sequelize 文档和论坛中搜索正确的语法,看来我的做法是正确的,但由于某种原因,密码字段仍在响应负载中返回...

以下link显示了我正在使用的属性排除语法是在 Sequelize 的 3.11 版中添加的:https://github.com/sequelize/sequelize/issues/4074

有人知道我在这里可能遗漏了什么吗?下面是 Create 方法和来自 Insert 语句的控制台日志。

Create方法

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

}

控制台日志

Executing (default): INSERT INTO "Users" ("id","firstName","lastName","email","password","createdAt","updatedAt") VALUES (DEFAULT,'James','Martineau','test@gmail.com','bANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2','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: 'bANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2', updatedAt: 2019-02-28T15:18:15.856Z, createdAt: 2019-02-28T15:18:15.856Z }...

快速阅读文档后,似乎 attributes 仅在以下查询中提及:

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

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

如果您想用 create 排除 password,您可以这样做:

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)

我在 document 中看到,当您 创建 模型时不能排除属性。仅在您 找到 模型时排除。

我建议:

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

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

尝试使用您想要的功能重载 Sequelize 模型 class。例如,运行 在应用 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;
    }, {});
  };

之后,您可以照常使用您的代码,但有一个 attributes 选项:

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

处理此问题的正确方法是在 Sequelize 公开的实际数据模型上利用 afterCreate 和 afterUpdate 挂钩。这些挂钩在记录持久化后触发,因此对数据值的任何更改只会反映在 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;
            },
        }
    }
);

这是文档的 link:https://sequelize.org/master/manual/hooks.html

我知道这是一个老问题,但这是我最近遇到的问题。 我解决这个问题的方法是这样的:

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

你可以像这样实例化你想要的字段,至少我在我的代码中到处都是这样做的

希望这对你也有用:)