Logo

dev-resources.site

for different kinds of informations.

Redis caching with Mongoose

Published at
10/1/2024
Categories
redis
caching
node
mongodb
Author
ayanabilothman
Categories
4 categories in total
redis
open
caching
open
node
open
mongodb
open
Author
14 person written this
ayanabilothman
open
Redis caching with Mongoose

If you are working with NoSQL databases and use the Mongoose package as an ODM to execute the queries on the database. This article is for you.

Why caching?

Caching is essential in optimizing performance, improving scalability, and enhancing the user experience of modern applications. It can significantly reduce the load on backend resources such as databases, or APIs. By serving cached data instead of executing resource-intensive operations.

How can we apply caching with Mongoose?

mongoose object imported from the mongoose package has a powerful other object called Query. We can add to its prototype any customized method. We will take advantage of this by creating a cache method, to be able to apply it on any query we need to cache its results.

As shown in the following code:

import mongoose from "mongoose";

mongoose.Query.prototype.cache = async function () {
  // generate unique redis key
  const filterObj = this._conditions;
  const options = this.options;
  const modelName = this.mongooseCollection.name;
  const findMethod = this.op;
  const redisKey = JSON.stringify({
    ...filterObj,
    ...options,
    ...{ model: modelName },
    ...{ method: findMethod },
  });

  // check if the result is chached before
  const cached = await client.hGet(modelName, redisKey);

  if (!cached) {
    const result = await mongoose.Query.prototype.exec.apply(this, arguments);
    client.hSet(modelName, redisKey, JSON.stringify(result));
    return result;
  }

  // cache the results
  const cachedResults = JSON.parse(cached);
  return Array.isArray(cachedResults)
    ? cachedResults.map((doc) => this.model.hydrate(doc))
    : this.model.hydrate(cachedResults);
};

app.get("/user", async (req, res) => {
  const users = await User.findOne({ age: { $gt: 30 } }).cache();
  return res.json({ results: users });
});
Enter fullscreen mode Exit fullscreen mode

In this code, we create a cache method that easily can be applied to any query. The logic of this method is simple :

1- generate a unique key name.

2- check if this key has a value cached before.

3- if yes, return the cached result.

4- if no, cache the query's result and return it.

Knowing that, the values are saved in a hash table, to optimize the performance.

With Query prototype we can add paginate method, for instance, or any other customized method to be applied to a query and write more clean code.

caching Article's
30 articles in total
Favicon
How to Implement Caching in PHP and Which Caching Techniques Are Best for Performance?
Favicon
Understanding Memcached: A Powerful In-Memory Caching Solution by Abhay
Favicon
Caching with Redis for Backend in Apache Superset
Favicon
The Most Popular Database Caching Strategies Explained
Favicon
Melhorando o Desempenho da Sua Aplicação PHP com Lithe Cache
Favicon
Cache Strategies: A Complete Guide with Real-Life Examples πŸš€
Favicon
Caching β€” An overview
Favicon
Bloom Filters
Favicon
HybridCache in ASP.NET Core - New Caching Library
Favicon
Advanced Data Caching Techniques for High-Performance Systems
Favicon
Redis: Understanding the Basics
Favicon
Implementing Caching Strategies for Improved Performance
Favicon
Improving the Performance of Your PHP Application with Lithe Cache
Favicon
Redis caching with Mongoose
Favicon
Building Scalable Web Applications: Techniques for Handling High Traffic
Favicon
πŸš€Optimize Web Performance in the Cloud with Caching!πŸš€
Favicon
Top 5 Next.js Caching Solutions for Next.js Apps (2024)
Favicon
Building a cache in Python
Favicon
Caching in .Net 8: Improving Application Performance
Favicon
Davide's Code and Architecture Notes - Cache Expiration vs Cache Eviction (and Eviction Policies)
Favicon
Conquering the Cache Calamity: My Journey to HNG Internship
Favicon
Next.js Caching Issues With Fetching Data
Favicon
MemoryCache in C#: A Practical Guide
Favicon
Caching & Memoization with state variables
Favicon
Laravel Caching - Explained Simply
Favicon
A way to cache responses in Grape API
Favicon
The Power of Caching and How to Implement It in Your Python Applications
Favicon
Caching
Favicon
Cost-Effective Image Management: Maximizing Efficiency Through Network Image Caching in Mobile Apps
Favicon
Top Redis Use Cases

Featured ones: