首页 > 解决方案 > 猫鼬redis缓存

问题描述

https://medium.com/@haimrait/how-to-add-a-redis-cache-layer-to-mongoose-in-node-js-a9729181ad69

在本指南中。所以我主要做这样的查询

{
id: <guild id>
}

所以每当创建新文档时。

 const book = new Book({
      title,
      content,
      author
    });

    try {
      await book.save();
      clearKey(Book.collection.collectionName);
      res.send(book);
    } catch (err) {
      res.send(400, err);
    }

如果我使用 {id: },它会从缓存中删除东西,还是只会删除缓存中类似于空对象或 Model#find() 的数据?

我还有另一个与此无关但可以问的问题。想象一下我这样做

const result = Model.findOne()

Cache.set(<anything>, JSON.stringify(result));
const cached = Cache.get(<anything>)
const result = new Model(cached);

result.message++;

await result.save().catch(console.error)

它抛出 MongoError: E11000 duplicate key error collection: How to fix that?

标签: javascriptmongodbmongooseredisdiscord.js

解决方案


clearKey(Book.collection.collectionName)简而言之,它将清除集合的所有缓存。


TLDR

你的情况this.hashKey = JSON.stringify(options.key || this.mongooseCollection.name);collectionName


https://redis.io/commands/hget

返回与存储在 key 的哈希中的字段关联的值。

clearKey(hashKey) {
    client.del(JSON.stringify(hashKey));
}

https://redis.io/commands/del

删除指定的键。如果键不存在,则忽略它。

因此,当您调用clearKey(Book.collection.collectionName);它时client.del,它将删除该特定集合的所有记录。因为完整的哈希被删除。


要删除特定字段而不是完整哈希:-

https://redis.io/commands/HDEL

从存储在 key 的哈希中删除指定的字段。此哈希中不存在的指定字段将被忽略。如果 key 不存在,则将其视为空哈希,此命令返回 0。


推荐阅读