简体   繁体   English

使用 Node.js 从 redis 列表中删除元素

[英]Deleting an element from redis list with Node.js

I was trying to manage a list in redis with nodejs.我试图用 nodejs 在 redis 中管理一个列表。 I am able to store list with following code :我可以使用以下代码存储列表:

client.rpush(['room_'+room, data.customClient], function(err, reply) {

        client.lrange('room_'+room, 0, -1, function(err, reply) {
          console.log(reply);
      });
    });

The console output is控制台输出是

[ 'POanqn9llyTcuIurUPAN', 'm9vd57wecp6JvtHOrRSJ' ] ['POanqn9llyTcuIurUPAN', 'm9vd57wecp6JvtHOrRSJ']

Now I want to delete one key POanqn9llyTcuIurUPAN from this list.现在我想从这个列表中删除一个键POanqn9llyTcuIurUPAN How can I do this ?我该怎么做?

It can be done through lrem command.它可以通过lrem命令完成。 The usage to delete all the entries with that value will be:删除具有该值的所有条目的用法是:

client.lrem('room_'+room, data.customClient, 0, 'POanqn9llyTcuIurUPAN', function(err, data){
    console.log(data); // Tells how many entries got deleted from the list
});

Here 0 is a count telling delete all the entries with the value POanqn9llyTcuIurUPAN in the given list.这里0是一个计数,告诉删除给定列表中值为POanqn9llyTcuIurUPAN 的所有条目。 From https://redis.io/commands/lrem the possible values of the count could be:https://redis.io/commands/lrem计数的可能值可能是:

  • count > 0: Remove elements equal to value moving from head to tail. count > 0:从头到尾删除等于 value 的元素。
  • count < 0: Remove elements equal to value moving from tail to head. count < 0:删除等于从尾部移动到头部的值的元素。
  • count = 0: Remove all elements equal to value. count = 0:删除所有等于 value 的元素。

it can be done easily like this:它可以像这样轻松完成:

client.lrem('room_'+room, 0, 'POanqn9llyTcuIurUPAN', function(err, data){
    console.log(data); // Tells how many entries got deleted from the list
});
client.del('POanqn9llyTcuIurUPAN', function(err, reply) {
    console.log(reply);
});

Or to check before: 或者之前检查:

client.exists('key', function(err, reply) {
  if (reply === 1) {
    client.del('POanqn9llyTcuIurUPAN', function(err, reply) {
      console.log(reply);
    });
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM