DEV Community

Cover image for Data Visibility: A Mongoose Middleware Case Study
Njabulo Majozi
Njabulo Majozi

Posted on

Data Visibility: A Mongoose Middleware Case Study

Situation: Unapproved orders displayed

As part of a recent feature development, the objective was to empower procurement officers to initiate orders on behalf of various departments. A critical requirement was to prevent these orders from appearing on departmental dashboards until formally approved by the respective department manager.

Tasks: Architectural decision

  • Option 1: Decentralised Filtering: Modify every single query that retrieves orders across the application. This approach presented a significant risk of identifying and changing potentially dozens or hundreds of queries that would be time-consuming; the likelihood of missing a critical query or introducing subtle bugs was significant, and leading to future changes to data visibility logic requiring similar widespread modifications.
  • Option 2: Centralised Interception (Chosen): Leverage Mongoose middleware to intercept all data retrieval operations. This promised a more robust and maintainable solution by centralising the logic for filtering unapproved orders at the data layer.

Actions: Filter out unapproved orders

  • To facilitate the filtering, I needed a mechanism to mark orders that were pending approval explicitly. We added a new field, activeAction, to our orderSchema

Schema

  • The core of our solution lies in a pre-find middleware hook. This hook executes automatically before any find operation (including findOne, findById, etc.) on the Order model.

Middleware

Results:

  • Clean and Accurate Dashboards: Only display approved and relevant order data and eliminating confusion.
  • Centralised Logic: The core filtering logic resides in a single, well-defined location within the orderSchema, making it easy to understand, debug, and modify.
  • Reduced Development Risk: We completely avoided the arduous and error-prone task of modifying numerous find queries throughout the application.
  • Scalable Pattern: This approach provides a reusable pattern for managing data visibility based on internal states, applicable to various entities beyond orders.

How do you use MongoDB middlewares? Share in the comments!

Top comments (0)