Mongoose Cache Manager
This module caches mongoose queries with cache-manager using an in-memory or Redis store.
Like many ODM cache solutions, the cache can only be kept fresh if this module is used for both reads and writes. When something writes directly to MongoDB without using mongoose, there is no way for this module to know it needs to reload fresh data into the cache.
In the future I want to try to improve this cache layer by using entity-based caching instead of only query caching.
Installation
$ npm install mongoose-cache-ts
or
$ yarn add mongoose-cache-ts
Usage
import { startRedisConnection, stopRedisConnection } from "mongoose-cache-ts";
// patch mongoose with default options
startRedisConnection({
host: "192.1.54.7", // host your redis
port: 6379, // port redis
time: 60, // time cache exist
password: "P1A2S3S4W5O6R7K8", // nullable
});
// Call when exist your app.
stopRedisConnection();
Then later any find
query will be cached for 60 seconds.
You can also enable/disable caching programatically by using the cache
method directly from the query instance:
const UserCollection = new Schema({...});
UserCollection
.find(condition)
.cache()
.then((err, docs) => {
if (err) throw error;
// do something with your database
});
When you want to populate or more out of queries. you can use the cache
method like:
UserCollection.find(condition)
.populate({
path: "profile",
// and more condition
})
.cache({
hashKey: {
populate: "profile",
},
})
.then((err, docs) => {
if (err) throw error;
// do something with your database
});
When you update, create or delete you want to reset redis:
import { clearKey, clearAllKey } from 'mongoose-cache-ts';
clearKey: will delete a key with data save in memory
example:
delete root key in UserCollection caching in memory
clearKey(UserCollection.collection.name);
clear all key in memory:
clearAllKey();