Reputation: 15
i have to "UPDATE" data in postgresql if data is already present in database and "INSERT" i.e create a new user_Id and insert data using IF condition. i have tried with this but i am not getting output. please help me if you know .
if(data.Details){
db.query('UPDATE Details SET fullName = $2,address= $3,phone = $4 WHERE user_id = $1 RETURNING *', [query, data.Details.fullName, data.Details.address, data.Details.phone],function(err,details) {
if (err) return callback(new Error('error'));
})
}else{
db.query('INSERT INTO Details(user_id,fullName,address,phone) VALUES($1,$2,$3,$4) RETURNING *', [query, data.Details.fullName, data.Details.address, data.Details.phone],function(err,details) {
if (err) return callback(new Error('error'));
})
}
Upvotes: 0
Views: 1527
Reputation: 8781
If you want to get fancy, you can also use UPSERT/ON CONFLICT in Postgres 9.5 and later.
It is designed for this exact use case, and executes as a single "instruction", rather than having to do a query check whether something exists, and another one to update or insert, both in a transaction.
Upvotes: 1