Node.js redis client. how can i use smember with a pattern?

Viewed 28

I have stored some keys with a pattern like this: 'user:id'

The id is unique.

Now I'm going to get all keys started with 'user' and also get their values.

This is my code to get values but it gives me an empty list.

const { createClient } = require('redis');

async function redisCatch() {
    const client = createClient();

    client.on('error', (err) => console.log('Redis Client Error', err));
    
    await client.connect();

    const value = await client.sMembers('user:*');
    console.log(value);
};

redisCatch();
1 Answers

Redis SMEMBERS doesn't allow you to input regex values for the key. See doc. You can do what you want using SCAN. Sample code:

const { createClient } = require('redis');

async function redisCatch() {
    const client = createClient();
    client.on('error', (err) => console.log('Redis Client Error', err));
    await client.connect();

    for await (const key of client.scanIterator({ MATCH: 'user:*' })) {
      const value = await client.sMembers(key);
      console.log(value);
    }
};


(async () => {
    await redisCatch();
})();
Related