JSPM

  • Created
  • Published
  • Downloads 1132
  • Score
    100M100P100Q107242F
  • License MIT

Cache plugin for mongoose Queries and Aggregate (in-memory, redis)

Package Exports

  • ts-cache-mongoose

Readme

ts-cache-mongoose

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

npm npm GitHub
Coverage Quality Gate Status
Reliability Rating Maintainability Rating Security Rating

npm

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": "16.x || 18.x || 20.x",
  "mongoose": ">=6.6.x || 7.x",
}

Features

  • In-memory caching
  • Redis caching
  • Cache expiration
  • Cache invalidation
  • Cache key generation
  • Cache key prefix
  • Query caching
  • Aggregate caching

Installation

  • Locally inside your project
npm install ts-cache-mongoose
yard add ts-cache-mongoose
  • This plugin requires mongoose >=6.6.x || 7.x to be installed as a peer dependency
# For mongoose 6
npm install mongoose@legacy
yarn add mongoose mongoose@legacy
# For mongoose 7
npm install mongoose@latest
yarn add mongoose@latest

Example

// On your application startup
import mongoose from 'mongoose'
import cache from 'ts-cache-mongoose'

// In-memory example 
const cache = cache.init(mongoose, {
  defaultTTL: '60 seconds',
  engine: 'memory',
})

// Redis example
const cache = cache.init(mongoose, {
  defaultTTL: '60 seconds',
  engine: 'redis',
  engineOptions: {
    host: 'localhost',
    port: 6379,
  },
})

mongoose.connect('mongodb://localhost:27017/my-database')

// Somewhere in your code
const users = await User.find({ role: 'user' }).cache('10 seconds').exec()
// Cache hit
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()

Check my other projects