DEV Community

prakash chokalingam
prakash chokalingam

Posted on

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)