Search code examples
node.jsredishashmap

How can I add an array to hash with hmset in redis


I store some key/value in a hash in redis. for example I have this json

{
"title": "CEO",
"originId": "52",
"status": "A"
}

My code to store this json is:

await redis.hmset(`role-${roleId}`, { title, originId, status })

So now I want to add an array of Ids as a mandatory field to this hash. So how can I add this array to this hash? My array is something like this:

 {
  "mandatories": ["119","120"],
 }

Solution

  • You can add it as another field in the same hash key, but stringify the array.

    await redis.hset(`role-${roleId}`, 'mandatories', JSON.stringify(mandatories))
    

    This way you can still HGETALL the whole role object data. But then, you have to manage the array of IDs as a whole.

    Or, you can flatten out the array to a list, set, or sorted set. For example, to add as set, you can do:

    await redis.sadd(`role-${roleId}-mandatories`, mandatories)
    

    Note we are adding '-mandatories' to the key name. Here you are passing the array to the node.js redis sadd function. It will add each array item as a member in the set. This allows you to manipulate the set of mandatories directly (SPOP, SREM, SISMEMBER, etc).

    Note that as per Redis 4.0.0, HMSET is considered deprecated. Use HSET instead.