Sunday, 16 April 2017

How to limit the result of a sequelize create() function to return only the values I want?

I am using Node.js and Express with Sequelize. I currently have a user model defined as:

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

Now to create a new user, I use the following code block:

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

And I get the following 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"
  }
}

I want to limit the data that is being exposed to the client who sees the response. I only want to show the username and email of the record so created. How to achieve such a thing in the Users.create() function?



via Pranjal Nadhani

No comments:

Post a Comment