Better way to do this with Node.js, Express, and MySQL?

Charles Pettis :

So I was wondering if anyone had a better method for my problem. Basically I want a record inside a record that I'm inserting into a database. What I mean is, I need to have a history of all the changes made to the record when updated. So whenever the record is updated, I save the info in a "Updates" column. Every time theres an update, I select the updates from that record, concatenate the new info onto the old updates and inserting it. See my code below.


app.post("/updateRecord", function(req,res){
  var prevResultUpdates = "";
  async function first(){
    con.query("SELECT * FROM Equipment WHERE Serial="+req.body.serial+" AND Part="+req.body.part, function(err,result,fields){
      if (err) throw err;
      console.log(result[0]['Updates'])
      return prevResultUpdates= prevResultUpdates + "," + result[0]['Updates']

    });
  }
  async function second(){
    await first();
    var customer = req.body.customer;
    var update = "\'" + prevResultUpdates + ',' + req.body.update + "," + Number(Date.now()) + "," + req.body.customer + ',' +"\'";
    var serial = req.body.serial;
    var part = req.body.part;
    var sql="Update `Equipment` SET `Customer`= '"+customer+"', `Updates`="+update+" WHERE Serial=" + serial + " AND Part=" + part;
    con.query(sql,function(err,result,fields){
      if (err) throw err;
      res.json(result)
    })
  }
  second();

  res.end()

})

Any thoughts on how to do this better?

O. Jones :

A bunch of suggestions here.

First, put a column in your table like this:

last_change TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

It will always contain the time of the most recent INSERT or UPDATE operation on each row, automatically without you needing to mention it in your SQL.

Second, be aware that

UPDATE Equipment SET Updates = Updates + ' some text string' 

works. You can change a column in place, without fetching its former value. But, this can fail when the column gets too long. So, do this instead.

UPDATE Equipment SET Updates = RIGHT(Updates + ' some text string', 255)

assuming your Updates column is defined as VARCHAR(255). I used RIGHT() rather than LEFT() because presumably the most recent update is the most interesting.

Third, you'd probably be wise to normalize this, to add an Equipment_history table. Instead of appending your update log to a column, insert a new row into Equipment_history. That table might have these columns

equipment_history_id  INT          primary key
equipment_id          INT          foreign key to Equipment table
customer              VARCHAR(255) identity of the customer 
update                VARCHAR(255) reason for update
last_change           TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

This lets you reconstruct the history of your updates if need be.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297429&siteId=1