cache-ka
About
A Mongoose caching library based on redis engine.
Usage
Add .cache()
method to query you want to cache. Works well with select
, skip
, limit
,lean
, sort
, and other query modifiers.
const mongoose = ;const cacheKa = ; ; Item // The number of seconds to cache the query. Defaults value is 60 seconds. Item // If ttl is set to 0 will store cache indefinetely.
Cache-ka allows you to store your cache with a custom prefix, that allows you to manage group of cached data.
const mongoose = ;const cacheKa = ; ; Item // Will create a redis entry with prefix cool_items. Item // Creates one more entry with prefix cool_items. //Clean cache for all queries with "cool_items" prefix.cacheKa;
Cache-ka also works with custom keys in your .cache()
query that allows you to remove cache by key.
const mongoose = ;const cacheKa = ; ; const parentID = '12052020'; Item // Will create a redis entry with key - 12052020_custom ItemSchema;
Clearing the cache
You can clean cache for a query with custom key, group of queries with a custom prefix and clean entire cache.
//For all queries related to prefix cacheKa; //For custom key. cacheKa; //Entire cachecacheKa;
Connecting to redis
Add you redis host
and port
as properties to options object of cache-ka initialisation.
It will create new redis client and connect it to your redis.
const mongoose = ;const cacheKa = ; ;
If you already has redis client you want to use you can pass it as redisClient
property ot options object
const mongoose = ;const cacheKa = ; const redis = ; const redisClient = redis ;
If you are using async-redis
library use redisClientAsync
property instead
const mongoose = ;const cacheKa = ; const redis = ; const redisClientAsync = redis ;
Caching populated documents
When a document returns from the cache, cache-ka hydrate it, which initializes its methods and virtuals. Hydrating a populated document will discard any populated fields (see Automattic/mongoose#4727). To cache populated documents without losing child items, use .lean()
, but it returns a plain object, so you will not be able to use methods and virtuals.