如何限制sequelize create()函数的结果只返回我想要的值?

时间:2017-04-16 16:28:14

标签: javascript node.js sequelize.js

我正在使用Node.js和Express with Sequelize。我目前的用户模型定义为:

const Users = sequelize.define("Users", {
    id: {
        type: DataType.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    username: {
        type: DataType.STRING,
        unique: true,
        allowNull: false,
        validate: {
            notEmpty: true
        }
    },
    email: {
        type: DataType.STRING,
        unique: true,
        allowNull: false,
        validate: {
            notEmpty: true,
            isEmail: true
        }
    },
    password: {
        type: DataType.STRING,
        allowNull: false,
        validate: {
            notEmpty: true
        }
    }
}

现在要创建一个新用户,我使用以下代码块:

  app.post("/register", (req, res, next) => {
    Users.create(req.body)
      .then(user => {
        res.json({
          status: "success",
          data: user
        });
      })
      .catch(err =>
        next(err)
      )
  });

我得到以下结果:

{
  "status": "success",
  "data": {
    "id": 6,
    "username": "brightuser",
    "email": "bright@user.com",
    "password": "$2a$10$xfWi5QFoEs0sFRyLrDqa7e77A4JTYoX.J/N5rK0QJFR2bf0AtWJZe",
    "updated_at": "2017-04-16T04:32:16.519Z",
    "created_at": "2017-04-16T04:32:16.519Z"
  }
}

我想限制向查看响应的客户端公开的数据。我只想显示如此创建的记录的用户名和电子邮件。如何在Users.create()函数中实现这样的功能?

2 个答案:

答案 0 :(得分:0)

Sequelize无法过滤create

上的数据

您有两个选项,您可以自己删除/选择不需要的数据,也可以在创建后进行提取并进行后续查找。

像这样:

const result = {
  "status": "success",
  "data": {
    "id": 6,
    "username": "brightuser",
    "email": "bright@user.com",
    "password": "$2a$10$xfWi5QFoEs0sFRyLrDqa7e77A4JTYoX.J/N5rK0QJFR2bf0AtWJZe",
    "updated_at": "2017-04-16T04:32:16.519Z",
    "created_at": "2017-04-16T04:32:16.519Z"
  }
}

delete result.data.password
delete result.data.updated_at
delete result.data.created_at

答案 1 :(得分:0)

DATA WANT; INPUT DATE :yymmdd10. TEAM $ TYPE $ Rate; format DATE yymmddd10.; datalines; 2020-07-26 Arsenal HOME 2.0 2020-07-26 Watford AWAY 3.6 2020-07-26 Burnley HOME 2.6 2020-07-26 Brighton AWAY 2.8 ; RUN; 承诺得到解决之后,您还可以像这样过滤数据;

create