Mongoose redis caching

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

In this guide. So I mostly do queries like

{
id: <guild id>
}

so whenever new document is created.

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

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

will it remove stuff from caches if i use {id: } or will it delete only data on cache that is like empty object or like Model#find()?

I also have another problem which is not related to that but could ask. Imagine I do this

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)

it throws the MongoError: E11000 duplicate key error collection: How to fix that?

Answer

clearKey(Book.collection.collectionName) In short, it will clear all the cache for the collection.


TLDR

In your case this.hashKey = JSON.stringify(options.key || this.mongooseCollection.name); is 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.

So when you call clearKey(Book.collection.collectionName); it calls client.del which will delete all the records for that particular collection. as the complete hash is deleted.


To delete specific fields not the full hash :-

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.