cachegoose
Mongoose caching that actually works.
About
A Mongoose caching module that works exactly how you would expect it to, with the latest version of Mongoose.
Important:
If you are using Mongoose 4.x or below, you need to use version 4.1 of this library.
Usage
var mongoose = ;var cachegoose = ; ; Record // The number of seconds to cache the query. Defaults to 60 seconds. ; Record // Explicitly passing in 0 will cache the results indefinitely. ;
You can also pass a custom key into the .cache()
method, which you can then use later to clear the cached content.
var mongoose = ;var cachegoose = ; ; var userId = '1234567890'; Children /* Will create a redis entry */ ; ChildrenSchema;
Insert .cache()
into the queries you want to cache, and they will be cached. Works with select
, lean
, sort
, and anything else that will modify the results of a query.
Clearing the cache
If you want to clear the cache for a specific query, you must specify the cache key yourself:
{ Children ;} { cachegoose;}
If you call cachegoose.clearCache(null, cb)
without passing a cache key as the first parameter, the entire cache will be cleared for all queries.
Caching populated documents
When a document is returned from the cache, cachegoose will hydrate it, which initializes it's virtuals/methods. Hydrating a populated document will discard any populated fields (see Automattic/mongoose#4727). To cache populated documents without losing child documents, you must use .lean()
, however if you do this you will not be able to use any virtuals/methods (it will be a plain object).
Test
npm test