18.5
18.5

Reputation: 31

How to read hash in redis using node.js using the HSCAN function?

I have a have set the hash using HSET function

async (userObject) => {
    const { phone } = userObject;
    const key = keyGenerator.getUserAuthKey(phone);

    try {
    for (const [field,value] of Object.entries(userObject)) {
        await redisClient.HSET(key,field,value);
    }
    logger.info(`------ user data cached in redis successfully`);
    return true;
    } catch (error) {
       logger.error(`Error in saving user data in redis : ${error.message}`);
       throw error
    }
}

and i have the following function to read the hash using HSCAN which give me an error saying TypeError: Cannot read properties of undefined (reading 'length') i hope i am missing some point on reading using HSCAN and can anyone help me please ? function to read using hscan

async function readRedisHashUsingHScan(hashKey) {
    let cursor = '0';
    const result = {};

    do {
        const reply = await redisClient.hScan(hashKey, cursor);
        const elements = reply[1]; 
        cursor = reply.cursor;
        for (let i = 0; i < elements.length; i += 2) {
            result[elements[i]] = elements[i + 1];
        }
    } while (cursor !== '0');

    return result;
}

and i am expecting to get a function that reads from a redis hash using hscan with a specific key

Upvotes: 1

Views: 109

Answers (1)

18.5
18.5

Reputation: 31

here is the function to read found it in the documentation

async function scanHash(hashKey) {
    const result = {};

    try {
        // Iterate over fields and values in the hash
        for await (const { field, value } of redisClient.hScanIterator(hashKey)) {
            result[field] = value;
            
        }
    } catch (error) {
        console.error('Error reading Redis hash:', error);
        throw error;
    }

    return result;
}

Upvotes: 1

Related Questions