ts-cache-mongoose
Cache query and aggregate in mongoose using in-memory or redis

Motivation
ts-cache-mongoose is a plugin for mongoose
Caching queries is a good way to improve performance of your application
Supports and tested with
{
"node": "18.x || 20.x || 22.x",
"mongoose": ">=6.6.x || 7.x || 8.x",
}
Features
- In-memory caching
- Redis caching
- Cache expiration
- Cache invalidation
- Cache key generation
- Cache key prefix
- Query caching
- Aggregate caching
- Supports ESM and CommonJS
Installation
- Locally inside your project
npm install ts-cache-mongoose
pnpm add ts-cache-mongoose
yarn add ts-cache-mongoose
bun add ts-cache-mongoose
- This plugin requires mongoose
>=6.6.x || 7.x || 8.x
to be installed as a peer dependency
npm install mongoose@6
pnpm add mongoose@6
yarn add mongoose@6
bun add mongoose@6
npm install mongoose@7
pnpm add mongoose@7
yarn add mongoose@7
bun add mongoose@7
npm install mongoose@8
pnpm add mongoose@8
yarn add mongoose@8
bun add mongoose@8
Example
import mongoose from 'mongoose'
import cache from 'ts-cache-mongoose'
const instance = cache.init(mongoose, {
defaultTTL: '60 seconds',
engine: 'memory',
debug: true,
})
const instance = cache.init(mongoose, {
defaultTTL: '60 seconds',
engine: 'redis',
engineOptions: {
host: 'localhost',
port: 6379,
},
debug: true,
})
mongoose.connect('mongodb://localhost:27017/my-database')
const users = await User.find({ role: 'user' }).cache('10 seconds').exec()
const users = await User.find({ role: 'user' }).cache('10 seconds').exec()
const book = await Book.findById(id).cache('1 hour').exec()
const bookCount = await Book.countDocuments().cache('1 minute').exec()
const authors = await Book.distinct('author').cache('30 seconds').exec()
const books = await Book.aggregate([
{
$match: {
genre: 'fantasy',
},
},
{
$group: {
_id: '$author',
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
author: '$_id',
count: 1,
},
}
]).cache('1 minute').exec()
await instance.clear()
const user = await User.findById('61bb4d6a1786e5123d7f4cf1').cache('1 minute', 'some-custom-key').exec()
await instance.clear('some-custom-key')
Check my other projects