3

I am trying to increment a value for a key-value in redis, if the value already exists in redis. For instance if we have

client.get(key, function checkRedis(err, data){
  var redisData = JSON.parse(data);
  if(redisData === null){
     //do something
  }else{
     client.incr(redisData.val);
  }
});

From my understanding, according to the documentation using "incr" should automatically increment that specific value by 1. But i am unable to see this happen successfuly, am i missing something

4

2 回答 2

3

You need to give client the key not the value.

I believe the below will do what you need.

client.get(key, function checkRedis(err, data){
  var redisData = JSON.parse(data);
  if(redisData === null){
     //do something
  }else{
     redisData.val++;
     client.set(key, redisData);
  }
});
于 2016-05-31T23:41:50.247 回答
0

您需要使用 INCR 键来增加 redis 中的值

   const redisClient = require('ioredis');
   const name = 'Bob';
   redisClient.incr('id', (err, id) =>
   {
      redisClient.hmset('user:' + id, 'username', name);
   });
于 2020-07-30T10:29:28.530 回答