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:
- 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.
- Implement this as a stored javascript function.
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.
精彩评论