Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

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

Use Case(s)

Code Examples

Example 1: Updating a Single Field in a JSON Object

This example demonstrates how to update a single field in a JSON object stored in Redis using the node-redis package along with the redis-json module.

const redis = require('redis');
const { promisify } = require('util');
const client = redis.createClient();
const setAsync = promisify(client.set).bind(client);
const getAsync = promisify(client.get).bind(client);

// Assuming you have previously set a JSON object
async function updateJsonField(key, field, value) {
    const jsonString = await getAsync(key);
    let jsonObject = JSON.parse(jsonString);
    jsonObject[field] = value;
    await setAsync(key, JSON.stringify(jsonObject));
    console.log(`Updated ${field} to ${value} in ${key}`);
}

// Usage
updateJsonField('user:1000', 'age', 30);

Explanation:

Example 2: Using RedisJSON Module for Efficient Updates

RedisJSON is a Redis module that allows natively handling, storing, and updating JSON documents. This example uses the ioredis package with RedisJSON.

const Redis = require('ioredis');
const redis = new Redis();

// Assuming you have previously set a JSON object using RedisJSON
async function updateJsonFieldRedisJSON(key, path, value) {
    await redis.call('JSON.SET', key, path, JSON.stringify(value));
    console.log(`Updated ${path} to ${JSON.stringify(value)} in ${key}`);
}

// Usage
updateJsonFieldRedisJSON('user:1000', '.age', 30);

Explanation:

Best Practices

Common Mistakes

FAQs

Q: Can I update nested fields within a JSON object in Redis?

A: Yes, using RedisJSON, you can update nested fields by specifying the path (e.g., user:1000, .address.city).

Q: Is the RedisJSON module required for handling JSON in Redis?

A: No, it's not required but highly recommended for efficiency and native JSON support. Without it, you'll need to handle JSON serialization and deserialization manually.

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