Nodejsにhsetとhmsetデータを格納



Hashデータ型

KEY
|_field1 : value1
|_field2 : value2
|_...
redisモジュールを使用する場合、ハッシュ・タイプのデータを次の3つの方法で入力できます.
client.HSET('key', {
  field1: 'value1',
  field2: 'value2'
});

client.HSET('key', ['field1', 'value1', 'field2', 'value2']);

client.HSET('key', [['field1', 'value1'], ['field2', 'value2']]);
キー値とフィールド値でロードします.
client.HMGET('key', ['field1', 'field2']);

サンプルコード


便宜上、簡単な変数名を使用します.
// redis.js
const CONFIG = require("../config/config");
const redis = require("redis");

// redis 연결 코드

module.exports = {
  set: async (key, value, second) => {
    // second가 있다면 set + expire 같이 설정
    if (second) return await client.SETEX(key, second, value);
    return await client.SET(key, value);
  },
  get: async (key) => {
    return await client.GET(key);
  },
  hset: async (key, fieldAndValue, second) => {
    /*
     *  ('key', { field1: 'value1', field2: 'value2'});
     *  ('key', ['field1', 'value1', 'field2', 'value2']);
     *  ('key', [['field1', 'value1'], ['field2', 'value2']]);
     */
    await client.HSET(key, fieldAndValue);
    if (second) await client.EXPIRE(key, second);
    return;
  },
  hget: async (key, feild) => {
    /*
     * .HMGET('key', ['field1', 'field2']);
     * .HGET('key', field);
     */
    if (Array.isArray(feild)) {
      return await client.HMGET(key, feild);
    }
    return await client.HGET(key, feild);
  },
  delete: async (key) => {
    return await client.DEL(key);
  },
};

const redis = require("redis.js");

// 값 넣기
await redis.hset("exampleKeyOne", {
  email: "[email protected]",
  nickname: "admin"
});

await redis.hset("exampleKeyTwo", [
  "email", "[email protected]",
  "nickname", "admin"
]);

await redis.hset("exampleKeyThree", [[
  "email", "[email protected]"],[
  "nickname", "admin"]
]);

// 값 불러오기
const one = await redis.hget("exampleKeyOne", ["email", "nickname"]);
console.log(one);
// [ '[email protected]', 'admin' ]

const two = await redis.hget("exampleKeyTwo", "email");
console.log(two);
// [email protected]

リファレンス


https://github.com/redis/node-redis/issues/1746