Taming the Complexity of Database Queries in Node.js
Hi, I'm John Fawcett
Dev@
Goodybag
Built Goodybag's REST API with Node + Postgres
Not a DB expert, but I'm alright
Why is Mongo Great?
JavaScript all the way down
Results are already JSON
Mongo shell is nice
Fast to setup
Well-documented
Queries built with JS primitives
Great for flex schemas
Learnboost did it
Code Sample
Why does Mongo Suck?
No transactions
No joining
Database locking on like EVERYTHING
Non-trivial use-cases can be really slow
Enter Postgres
Take the good, drop the bad
Relational
Transactions
JSON Support (flexible schemas)
Pretty darn fast
(Page 39)
Widely used
What does it look like in node?
SQL Tools
Don't write SQL strings in JS - Use:
Node SQL (
See Code
)
Silly SQL (
See Code
)
MongoSQL
Example 1
Example 2
Example 3
Example 4
Example 5
MongoSQL: What is it good for?
Not for easier SQL writing
It's for easier SQL reasoning inside of code
Your query becomes a value
Robust helper interface - your use-case is supported
Makes SQL composable and extensible
Helps tame queries
like this
Helps you build your
own
tools when rolling your own is necessary
Closing the Gaps and the Mental Leaps
MoSQL brings it back to JavaScript
Further decreases the mental gap between database and code
What About ORMS?
MoSQL && ORMs not mutually exclusive
Sequelize.js - great monolithic choice
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function sequelize.query
The need for an ORM is partially obviated in JS
Often, ORMs complect a situation more than simplify it
MoSQL can help you build your own ORM
Example: When SQL Attacks
New features need to be added
How do we organize
monsterous
queries?
Proper logic chunking
Maybe your API needs to be slightly denormalized
Without degrading performance
In Sequelize, you'd probably write batch queries (with bad performance)
Use-case isn't supported, so you end up writing SQL anyway
Use MoSQL to help
Conclusion
In the end, I use a combination of Silly and MoSQL
Use Postgres and MoSQL - close the mental gap
MoSQL is super extensible, composable, and supports a lot of use cases
Database queries as a simple, reflectable data structure
Helps build your own tools and separate your logic
Recent project: generic middleware and ORM-ish tools