My rest api calls Put request to this function to create firebase token on Postgre-sql.
However, I realized whenever the token gets refreshed a new row will be added for the same user.
How do I make it so that it'll perform a insert if it exists and updates if it doesn't.
I've already tried on conflict update, but it doesn't work.
The code is here :
function createUserToken(req, res, next) {
var userid = req.user.email;
db.none('insert into fcmdb(userid, token)'+
'values($1, $2) on conflict update',
[userid,req.body.token])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted token'
});
})
.catch(function (err) {
return next(err);
});
}
This is just because are directly inserting the data with the help of insert query. What you should have done is firstly you need to check with the help of userId what does that user id exist in your db it yes then you need to update the else just insert is as you are doing
Or
The way you are doing you can use this example as a reference(use DUPLICATE KEY UPDATE insted of on conflict update) INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;