node.js - 为什么我会收到以下 Redis 警告和错误?

标签 node.js redis

当我尝试将以下数据保存到 Redis 时:

{ _id: 5c9535a742e1ce2b2ce90be5,
  email: 'admin@admin.com',
  items:
   [ { _id: 5c9535c042e1ce2b2ce90be6, product: [Object], quantity: 1 },
     { _id: 5c9535c642e1ce2b2ce90beb, product: [Object], quantity: 1 } ],
  createdOn: 2019-03-22T19:21:11.349Z,
  __v: 0 }

我收到以下警告:

node_redis: Deprecated: The SETEX command contains a argument of type model.
This is converted to "{ _id: 5c9535a742e1ce2b2ce90be5,
  email: 'admin@admin.com',
  items:
   [ { _id: 5c9535c042e1ce2b2ce90be6, product: [Object], quantity: 1 },
     { _id: 5c9535c642e1ce2b2ce90beb, product: [Object], quantity: 1 } ],
  createdOn: 2019-03-22T19:21:11.349Z,
  __v: 0 }" by using .toString() now and will return an error from v.3.0 on.
   Please handle this in your code to make sure everything works as you 
intended it to.

当我尝试从 Redis 检索数据时,出现以下错误:

undefined:1
  { _id: 5c9535a742e1ce2b2ce90be5,
    ^
  SyntaxError: Unexpected token _ in JSON at position 2
   at JSON.parse (<anonymous>)

用于保存到Redis的函数:

exports.setCart = (email, cart) => {
    cart - JSON.stringify(cart);
    redisClient.setex(email, CACHE_TTL, cart);
}

用于从 Redis 检索数据的函数:

exports.getCart = (email, callback) => {
    redisClient.get(email, (err, cart) => {
        if(err) {return callback(err, null)}

        console.log('CART FROM CACHE ', cart)
    return callback(err, JSON.parse(cart));
    })
}

保存数据到redis的函数调用:

redisClient.setCart(email, cart);

最佳答案

我不认为 redis 能够直接处理 JSON 对象——尤其是嵌套的 JSON。您可以将一个简单的 JSON 对象存储为散列(我所说的简单是指它是一个平面 JSON,没有包含其他嵌套 JSON 对象的属性)。

最简单的解决方案是在存储之前对所有内容进行 JSON.stringify(),然后在检索它们时对它们进行 JSON.parse()

如果您的对象不是太大,这很好,但它仍然不理想。另一种选择是使用 flat npm 包,它基本上可以将嵌套的 JSON 扁平化,以便将它们存储为哈希。您可以在 this 上查看有关它的更多信息中等文章。

关于node.js - 为什么我会收到以下 Redis 警告和错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55622890/

相关文章:

SQL Server批量插入抛出请求超时错误?

redis - 使用 Redis INCR 超过 Int64 最大值时会发生什么

ruby-on-rails - 如何使用 Foreman 正确关闭和转储 Redis 服务器?

Laravel Redis 缓存

node.js - 无法使用 Admin SDK 在 Firestore 模拟器中获取 FieldValue.increment

javascript - aasy 函数结束后返回函数的值

javascript - Node.js 类型错误 : Invalid non-string/buffer chunk

javascript - 用 Nodejs 写标准输出

memory - Redis 最佳哈希集条目大小

database - Redis 适合我需要的东西吗