Ethan Richardson
Ethan Richardson

Reputation: 491

Updating a redis client hash

I would like to update and add an item to the redis hash session entry.

I have been able to create a hash using the redis client using the code below:

var redis = require('redis');
var client = redis.createClient(); //creates a new client

client.on('connect', function() {
    console.log('connected');
});

client.hmset('frameworks', {
    'javascript': 'AngularJS',
    'css': 'Bootstrap',
    'node': 'Express'
});

Is there a way of adding to this hash? I would like to change and also to update an existing hash element.

Is this possible without reading everything and creating a new hash with updated and new hash elements.

I am using this webpage as a tutorial guide : https://www.sitepoint.com/using-redis-node-js/

Upvotes: 4

Views: 13940

Answers (2)

Dario
Dario

Reputation: 4035

Yes, if the key or hash field already exists in the hash, they are overwritten.

So, to add or update one field you can use hset, or hmset if you want to insert/upsert multiple fields.

If you want to overwrite the entire hash with a new one discarding previous values, you can use client.multi() and use a combination of del and hmset commands, to execute them in a transaction.

Upvotes: 4

jerry
jerry

Reputation: 745

You can use same hmset/hset based on how many you want to add or update

var redis = require('redis');
var client = redis.createClient(); //creates a new client

client.on('connect', function() {
    console.log('connected');
});

client.hmset('frameworks', {
    'javascript': 'AngularJS',
    'css': 'Bootstrap',
    'node': 'Express'
});

Say you initially have this and want to add db : mongo, and want to update node: Express4 then you can just use

//If you know will update only one use hset instead
client.hmset('frameworks', {
    'node': 'Express4',
    'db' : 'MongoDB'
});

Will add db & update node too for the key frameworks

Upvotes: 12

Related Questions