猫鼬redis缓存

Mongoose redis caching

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 重复键错误集合: 如何解决?

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


TLDR

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


https://redis.io/commands/hget

Returns the value associated with field in the hash stored at key.

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

https://redis.io/commands/del

Removes the specified keys. A key is ignored if it does not exist.

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


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

https://redis.io/commands/HDEL

Removes the specified fields from the hash stored at key. Specified fields that do not exist within this hash are ignored. If key does not exist, it is treated as an empty hash and this command returns 0.