MongoJS Models is a lightweight MongoDB object modeling library for node.js. It uses mongojs as backend API, and expands from there by providing classes for Models and Schemas.
For basic usage, refer to the mongojs API documentation. In addition to the MongoDB API calls, MongoJS Models provides object modeling capabilities.
// Require libraries and initiate database connectionvar db = connectionString;// Define your schemavar schema =firstName: StringlastName: String;// Instantiate your Model class for the 'users' collectionvar User = 'users' schema;
Now that your Model class is instantiated, you can use model prototype methods:
var user = firstName: 'John' lastName: 'Doe';user;user;
You also have access to static collection methods:
You can add hooks to a Model class to run functions on any given document prior to it being saved. This allows you to modify documents before sending them to MongoDB. To add pre-save hooks:
The document to be saved is bound directly to
this. Pre-save methods have a
next, which is a callback, to allow for asynchronous
Pre-save hooks are run in the order they were registered, and the changes to a document are cumulative.
Model class itself is evented. This means that you can listen to events
on the static class, rather than on instances. This allows for more complex
modeling behavior. Following the example above:
Events emitted by default are
remove, but you can also emit any
custom event by doing:
See the API documentation for a list of all static collection methods.