0

I need to insert multiple json value into a mysql column. Here I have a table named client

query = ' INSERT INTO client (user_id,client_id,tenant_id) values ?'
let queryClient = []
queryClient.push(clientData.user_id)
queryClient.push(clientData.client_id);
queryClient.push(clientData.tenant_id);

Before that I assigned req.body into clientData

Here is the connection to the mysql database

var queryMapClientIn = mysql.format(query, [queryClient])
const newMapClient = await conPool.query(queryMapClientIn, function (err, result) {
  if (err) throw err;
  console.log("Number of records inserted: " + result.affectedRows);
});

This is the code and json data is:

{
    "user_id" : 101,
    "client_id": 999,
    "tenant_id" : 1,
    "additionalClient" : [
        {"user_id" : 130},
        {"user_id" : 131}
    ]
}

Here is the json data and i need to push multiple user_id into user_id column on sql table. Can I get to know how to insert multiple user_id on this table.

0

1 Answer 1

1

You can create a 2-dimensional array to insert multiple rows.

let clientData = {
    "user_id" : 101,
    "client_id": 999,
    "tenant_id" : 1,
    "additionalClient" : [
        {"user_id" : 130},
        {"user_id" : 131}
    ]
};
let queryClient = [[clientData.user_id, clientData.client_id, clientData.tenant_id]];
if (clientData.additionalClient) {
    let additionalClients = clientData.additionalClient.map(({user_id}) => [user_id, clientData.client_id, clientData.tenant_id]);
    queryClient = queryClient.concat(additionalClients);
}

let query = 'INSERT INTO client (user_id,client_id,tenant_id) values ?';
const newMapClient = await conPool.query(query, queryClient, function (err, result) {
  if (err) throw err;
  console.log("Number of records inserted: " + result.affectedRows);
});
Sign up to request clarification or add additional context in comments.

9 Comments

Its showing map is map is undefined and it cannot read the property. Can I know what is the use of map here
That means that there's no clientData.additionalClient property like you showed.
Read it carefully. It doesn't say that map is undefined, it says that clientData.additionalClient is undefined, since that's what we're trying to access the map property of.
additional_client != additionalClient
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.