使用Sequelize Create方法时如何仅返回特定属性

时间:2019-02-28 15:36:10

标签: javascript sequelize.js sequelize-cli

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

以下链接显示了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)
};

}

控制台日志

  

执行(默认):插入“用户”   (“ id”,“ firstName”,“ lastName”,“ email”,“ password”,“ createdAt”,“ updatedAt”)   价值   (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')返回*;

     

USER:用户{{dataValues:       {id:6,         firstName:“詹姆斯”,         lastName:“ Martineau”,         电子邮件:“ test@gmail.com”,         密码:          '$ 2b $ 10 $ 7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2',         更新时间:2019-02-28T15:18:15.856Z,         createdAt:2019-02-28T15:18:15.856Z} ...

6 个答案:

答案 0 :(得分:1)

通过快速阅读文档,似乎只在以下查询中提到了C:\Users\WDKRemoteUser\Desktop\Debug>testvhid.exe ....looking for our HID device (with UP=0xFF00 and Usage=0x01) Warning: CreateFile failed: 5 Warning: CreateFile failed: 5 Failure: Could not find our HID device

x_min, x_max = numpy.pi/10, numpy.pi
y_min, y_max = 1e-7, 1e-5
xs = numpy.linspace(x_min, x_max, 10)
ys = numpy.linspace(y_min, y_max, 10)
results = numpy.zeros((len(xs), len(ys)))
for i, x in enumerate(xs):
    for j, y in enumerate(ys):
        results[i,j] = function(x,y)

pyplot.figure(figsize=(15,15))
pyplot.xlim(x_min, x_max)
pyplot.ylim(y_min, y_max)
pyplot.xticks(xs)
pyplot.yticks(ys)
im = pyplot.imshow(results,
                    extent=(x_min, x_max, y_min, y_max),
                    origin='lower',
                    cmap=matplotlib.cm.gray)
pyplot.colorbar(im, orientation='vertical', label='energy')
pyplot.show()

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

如果您想将attributes排除在Model.findAll({ attributes: { exclude: ['baz'] } }); 之外,则可以执行以下操作:

password

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

尝试使用所需功能重载Sequelize Model类。例如,在应用程序引导期间运行以下代码一次:

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

答案 3 :(得分:1)

处理此问题的正确方法是利用Sequelize公开的实际数据模型上的afterCreate和afterUpdate挂钩。在记录保留之后将触发这些钩子,因此dataValues的任何突变都将仅反映在返回中。

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

以下是文档的链接:https://sequelize.org/master/manual/hooks.html

答案 4 :(得分:0)

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

答案 5 :(得分:0)

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

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

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

希望这对你也有用:)