Node.js Update information in mysql
Tags: node
Published: 2020-11-01 13:53:58

I am trying to implement a function that will update information in the database in MySQL. I cannot find a way to solve this problem. whereby postman is not reading my id, username, email. I manage to make the login and registration to work in my react.js website. but now I want to allow users to able to edit their profile information.

customer.model.js
``` js 
const sql = require("../config/db.config");

const Customer = function(customer) {
    this.email = customer.email;
    this.username = customer.username;
    this.id = customer.id;
    
  };

  Customer.updateById = (customer) => {
    sql.query(
      "UPDATE users SET username = ?, email = ? WHERE id = ?",
      [customer.email, customer.username, customer.id],
      (err, res) => {
        if (err) {
          console.log("error: ", err);
          result(null, err);
          return;
        }
  
        if (res.affectedRows == 0) {
          // not found Customer with the id
          result({ kind: "not_found" }, null);
          return;
        }
  
        console.log("updated customer: ", { id: id, ...customer });
        result(null, { id: id, ...customer });
      }
    );
  };
```
auth-controller.js
``` js
const db = require("../models");
const config = require("../config/auth.config");
const Customer = require("../models/customer.model.js");
const User = db.user;
const Role = db.role;

const Op = db.Sequelize.Op;

var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");

exports.signup = (req, res) => {
  // Save User to Database
  User.create({
    username: req.body.username,
    email: req.body.email,
    password: bcrypt.hashSync(req.body.password, 8)
  })
    .then(user => {
      if (req.body.roles) {
        Role.findAll({
          where: {
            name: {
              [Op.or]: req.body.roles
            }
          }
        }).then(roles => {
          user.setRoles(roles).then(() => {
            res.send({ message: "User registered successfully!" });
          });
        });
      } else {
        // user role = 1
        user.setRoles([1]).then(() => {
          res.send({ message: "User registered successfully!" });
        });
      }
    })
    .catch(err => {
      res.status(500).send({ message: err.message });
    });
};

exports.signin = (req, res) => {
  User.findOne({
    where: {
      username: req.body.username
      
    }
  })
    .then(user => {
      if (!user) {
        return res.status(404).send({ message: "User Not found." });
      }

      var passwordIsValid = bcrypt.compareSync(
        req.body.password,
        user.password
      );

      if (!passwordIsValid) {
        return res.status(401).send({
          accessToken: null,
          message: "Invalid Password!"
        });
      }

      var token = jwt.sign({ id: user.id }, config.secret, {
        expiresIn: 86400 // 24 hours
      });

      var authorities = [];
      user.getRoles().then(roles => {
        for (let i = 0; i < roles.length; i++) {
          authorities.push("ROLE_" + roles[i].name.toUpperCase());
        }
        res.status(200).send({
          id: user.id,
          username: user.username,
          email: user.email,
          roles: authorities,
          accessToken: token
        });
      });
    })
    .catch(err => {
      res.status(500).send({ message: err.message });
    });
};

exports.update = (req, res) => {
  // Validate Request
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
  }

  console.log(req.body);

  Customer.updateById(
    req.body.customerId,
    req.body.username,
    req.body.email,
    new Customer(req.body),
    (err, data) => {
      if (err) {
        if (err.kind === "not_found") {
          res.status(404).send({
            message: `Not found Customer with id ${req.params.customerId}.`
          });
        } else {
          res.status(500).send({
            message: "Error updating Customer with id " + req.params.customerId
          });
        }
      } else res.send(data);
    }
  );
};
```
auth.routes.js
``` js
const { verifySignUp } = require("../middleware");
const controller = require("../controllers/auth.controller.js");

module.exports = function(app) {
  
  app.use(function(req, res, next) {
    res.header(
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8081'),
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'),
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'),
      res.setHeader('Access-Control-Allow-Credentials', true),
      "Access-Control-Allow-Headers",
      "x-access-token, Origin, Content-Type, Accept"
    );
    next();
  });

  app.post(
    "/api/auth/signup",
    [
      verifySignUp.checkDuplicateUsernameOrEmail,
      verifySignUp.checkRolesExisted
    ],
    controller.signup
  );

  app.post("/api/auth/signin", controller.signin);

  app.put("/api/auth/update", controller.update);
};



```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g06y4n4r0gaop6v13z9u.png)