1

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);
    });
}
boraseoksoon
  • 2,164
  • 1
  • 20
  • 25
  • Possible duplicate of [How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?](http://stackoverflow.com/questions/17267417/how-to-upsert-merge-insert-on-duplicate-update-in-postgresql) – vitaly-t Oct 22 '16 at 11:31

1 Answers1

1

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;

Shumi Gupta
  • 1,505
  • 2
  • 19
  • 28
  • 1
    Thanks, managed to make it work with insert into fcmdb(userid, token) values('test1@example.com','HELLO') ON CONFLICT (userid) DO UPDATE set token='HELLO';. Also i forgot to set userid as the primary key and that fixed it. – Mark Angelo Lim Oct 23 '16 at 23:09