M gowda
M gowda

Reputation: 203

How to insert array of values in postgresql using nodejs

for(i in req.body.category_id){
db.query('INSERT INTO guide_categories(category_id) values($1)', [req.body.category_id[i]],function(err,category) {
  if(err) return next(err);                         
  return console.log("success");           
  });                             
}
Here I am passing the array of values from postman as category_id:["3","1"], and only the last value of the array is being inserted and the rest are not. How do I solve this?

Upvotes: 2

Views: 4495

Answers (1)

Vao Tsun
Vao Tsun

Reputation: 51416

change to

for(i in req.body.category_id){
db.query('INSERT INTO guide_categories(category_id) values($1) returning *', [req.body.category_id[i]], (err,category) => {
  if(err) {
    console.log(err);     
    } else {                    
    console.log(category);   
  }        
  };                             
}

and populate the output of console.log

Upvotes: 1

Related Questions