DEV Community

prakash chokalingam
prakash chokalingam

Posted on

5

Codebytes: Caching mongoose models in Redis (MongoDB).

Ever considered caching your mongoose models in a super caching tool like Redis to avoid frequent MongoDB hit and refrained from doing that because you may lose the mongoose object privileges like calling model._id as model.id or model.toObject() or the superior one model.populate() and others.

Here comes the saviour,
https://mongoosejs.com/docs/api.html#model_Model.hydrate

Hydrate method in mongoose API converts your raw JSON data into the mongoose model object(s).

Example: Simple model

// set cache

let todo = Todo.findById(id);
redis.set(key, todo); // stores as raw json

// read cache

let todoCache = redis.get(key); // returns raw json
let todo = Todo.hydrate(todoCache); // converts in to mongoose model

let createdBy = todo.populate('createdBy'); 
Enter fullscreen mode Exit fullscreen mode

Example: Array of models

// set cache

let todos = Todo.findAll();
redis.set('todos', todos); // stores as array of son

// read cache

let cachedTodos = redis.get('todos'); // returns array of json
let todos = cachedTodos.map(todo => Todo.hydrate(todo)); // converts in to mongoose model

let incompleteTodos = todos.filter(todo => !todo.isDone);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay