Reputation: 25
I'm quite new to this stuff, but after few attempts, I would like to ask you for a help here, because I'm not sure, what exactly I'm doing wrong.
Situation: In Redis database, I got a key test
with values like 1,2,3,4
. To put new value into key, I use rpush
, because I want to add new value at the end of the key (and when I run this standalone, it works as a charm):
client.rpush("test", "5");
However, my idea is, that first I would like to check out, if the key exists and if not, then I will add a value into it. For that I decided to use LRANGE command, now result looks like this:
client.lrange("test", 0, 0, function(err, reply) {
if (reply.length === 0) {
client.rpush("test", 5);
}
Problem is, that in case described above, rpush
seems to be 'ignored', it will not store the value. What am I doing wrong? It looks like any Redis command inside lrange
callback is ignored.
Upvotes: 0
Views: 1298
Reputation: 765
It sounds like you may be wanting to use LLEN
instead of LRANGE
.
https://redis.io/commands/llen
I am not a node guy, but something like this should work. Your example should work though, if this doesn't clear it up I would go ahead and update your description to include some logging.
client.llen('test', function(err, reply) {
if (err) {
// Log error
}
// Log reply
if (reply === 0) {
client.rpush('test', 5, function(err, reply) {
if (err) {
// Log error
}
// Log reply
})
}
})
Upvotes: 2