riceplate
riceplate

Reputation: 121

Multi row insert using Knex.js

Am trying to build an multi-row insert query using Knex.js

My post request contains a variable which is formatted in the following format : [{addon_name:'sugar'},{addon_name:'milk'}]

My DB table has only one column namely addon_name

My knex query in my node application goes as follows

knex(`<table_name>`).insert(req.body.`<param_name>`))

expected op

insert into `<tablename>`(`addon_name`) values (sugar), (milk);

but the code dosn't work. Any comments ?

Error Details

{ [Error: insert into `table_name` (`0`, `1`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `2`, `20`, `21`, `22`, `23`, `24`, `25`, `26`, `27`, `28`, `29`, `3`, `30`, `31`, `32`, `33`, `34`, `35`, `36`, `37`, `38`, `39`, `4`, `40`, `41`, `5`, `6`, `7`, `8`, `9`) values ('[', '{', 'm', 'e', ':', '\'', 's', 'u', 'g', 'a', 'r', '\'', 'a', '}', ',', '{', 'a', 'd', 'd', 'o', 'n', '_', 'n', 'd', 'a', 'm', 'e', ':', '\'', 'm', 'i', 'l', 'k', '\'', 'd', '}', ']', 'o', 'n', '_', 'n', 'a') - ER_BAD_FIELD_ERROR: Unknown column '0' in 'field list']
  code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sqlState: '42S22',
  index: 0 }

Upvotes: 9

Views: 25734

Answers (4)

Himanshu Shekhar
Himanshu Shekhar

Reputation: 1262

You can use batch insert

DB.transaction(async (t: Knex.Transaction) => {
return await t
  .batchInsert("addon_name", addon_nameRecords)
  .returning("id");
});

Upvotes: 1

Akshay Raje
Akshay Raje

Reputation: 892

Though this is an old question, I am replying here just for others who stumble upon this.

Knex now supports multi-row inserts like this:

knex('coords').insert([{x: 20}, {y: 30},  {x: 10, y: 20}])

outputs:

insert into `coords` (`x`, `y`) values (20, DEFAULT), (DEFAULT, 30), (10, 20)

There's also the batchInsert utility will inserts a batch of rows wrapped inside a transaction.

Upvotes: 9

riceplate
riceplate

Reputation: 121

Thanks. I changed the structure of my input in post method, to an comma separated string. That way it gets easier to parse the input and model it the way I need.

post method input : "milk,sugar"

code

//Knex accepts multi row insert in the following format [{},{}] => we need to 
//model our input that way
var parsedValues = [];
try {
    var arr = req.body.addons.split(',');
}catch(err){
    return res.send({ "Message": "405" }); // Data not sent in proper format
}

for (var i in arr) {
    parsedValues.push({addon_name: arr[i]});
}
console.log(parsedValues);

knex(`<table_name>`).insert(parsedValues).then(function (rows){ 
    console.log(rows);
    return res.send({ "Message": "777" }); // Operation Success
}).catch(function (err){
    console.log(err)
    return res.send({ "Message": "403" }); // PK / FK Violation
});

Upvotes: 1

Selfish
Selfish

Reputation: 6200

req.body.<param_name> is always a string. Most probably this will work for you:

knex(table_name).insert(JSON.parse(req.body.param_name)));

What you are seeing in your error is Knex treating the string as an array of chars, trying to push it to the table.

In the error, the following:

values ('[', '{', 'm', 'e', ':', '\'', 's', ...

Is actually your string being broken down: [{me:\'s....

Upvotes: 1

Related Questions