Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

Redis ZADD in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

The ZADD command in Redis is used to add one or more members to a sorted set, or to update the score for members that already exist. Common use cases include:

Code Examples

Example 1: Adding Single Member to Sorted Set

This example demonstrates how to add a single member with a score to a sorted set using Node.js Redis client.

const redis = require('redis');
const client = redis.createClient();

client.on('connect', () => {
   console.log('Connected to Redis server.');
});

const key = 'leaderboard';
const score = 50;
const member = 'user123';

client.zadd(key, score, member, (err, response) => {
    if (err) throw err;
    console.log(`Number of elements added: ${response}`);
});

client.quit();

Example 2: Adding Multiple Members to Sorted Set

This example shows how to add multiple members with their scores to a sorted set.

const redis = require('redis');
const client = redis.createClient();

const key = 'leaderboard';
const members = [
    45, 'user1',
    70, 'user2',
    55, 'user3'
];

client.zadd([key, ...members], (err, response) => {
    if (err) throw err;
    console.log(`Number of elements added: ${sponse}`);
});

client.quit();

Best Practices

Common Mistake

FAQs

Q: Can I update the score of an existing member using ZADD?
A: Yes, if a specified member is already present in the sorted set, its score will be updated, and the element repositioned accordingly.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost