Dragonfly Cloud announces new enterprise security features - learn more

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:

  • Leaderboards or ranking systems where items are scored and ranked.
  • Storing and retrieving items with some notion of priority or weight.

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

  • Connection Management: Ensure to close the Redis connection properly using client.quit() to free up resources.
  • Error Handling: Always handle errors in callbacks to prevent unhandled exceptions.

Common Mistake

  • Data Type Confusion: Ensure that the score is a number. Passing it as a string can lead to unexpected results because Redis sorts scores lexicographically when they're strings.

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?

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