mysqlnode.jsnode-sqlserver

Using mssql and node-sql to UPDATE


I'm using mssql together with node-sql to build SELECT queries but I can't find any example how to use it to build UPDATE queries. I have an object where properties corresponds to table fields and I would like to update all of them.

Assume:

child: sql.define({
    name: 'children',
    columns: ['id', 'name', 'surname', 'group']
  })

and:

var data = {/*new child data*/};

var query = child.update(data).where(child.id.equals(data.id)).toQuery().text;

How can I use this with mssql without knowing values and count of data properties?

Right now I have this:

connection.query(query, [data.id, data.name, data.surname, data.group], function(err, result) {

      res.redirect('/index');
    });

that can be achieved by using lodash's values:

_.values(data);

which returns array of object properties but it does not guarantee correct order which is deal breaker.

How can I tackle that problem?


Solution

  • This will return an array of values based on the order of table columns:

    child.columns.map(function(col){return data[col.name]})
    

    It might be possible to compact the above in shorter form with lodash.