Q: Why do people use mongoose?
Here are some of the benefits:
- You can execute commands right away without having to wait for
mongo.connect()
- You get schema validation
- You can create synthetic joins via populate
However, there are some potential downsides:
- Mongoose is global object - causing potential conflicts
- Mongoose can be very slow with all the getters, setters and whatnot
- the
lean()
options ends up being slower than native - It can be difficult to understand what is going on behind the scenes
- The schema is non-standard
Moongoose to the rescue
- Just over 100 LOC - simple wrapper around native
- No need to wait for connection before executing commands
- Efficient
populate
for streaming and findOnes - Validation with JSON schema
- Acts global but can be cloned for ringfencing different instances
Examples
Example: fetching data
var moongoose = ; moongoose; // Find one record and populatemoongoose ; // Find all record, populate and streammoongoose ; // Find all records, poopulate and capture into arraymoongoose
Example: save a record with validation
var test = moongoose; // This successfully save the record - junk is removed in validationtest; // This fails validation and is not savedtest; // This passes json-schema validation but fails custom validationtest;