tags:

views:

13

answers:

1

I'm writing an API which uses MongoDB as the storage backend. Let's say the API allows a consumer to query for upcoming events. Let's say some events are private, and for the current user, should not come up in the results. Should I:

  1. Implement this at the API level. The API code, will be responsible for these checks. The advantage seems to be that if I change storage engines (unlikely), the business code will be intact.
  2. Implement this as a stored javascript function.
A: 

At the API level, for the reason you mentioned: you're independent of the underlying storage mechanism of your application.

A good guideline is Persistence Ignorance: make your business logic as little aware of the storage mechanism as possible. This implies that business logic shouldn't be located in your storage layer either. So stored procedures or stored JavaScript functions shouldn't contain business logic. Some advantages of this:

  • You can swap the underlying database with minimal effort and without having to re-implement your business logic in the new database.
  • All of your business logic is contained inside your application layer, making the code base easier to understand and debug.

The only functions you should store in MongoDB are 'utility' functions; functions that simplify common operations, such as string operations, but are not tied to your business logic in any way.

Niels van der Rest