express-mongoose-helper
adds app.model() function and app.model[ModelName] to express.
install
npm install --save express-mongoose-helper
basic info
module signature
app.model function signature
for legacy reasons, schemaOptions and callback may be given in either order, or not at all.
app
model file signature (Note: you can edit what is injected to the required module, these are the defaults.)
each model file should export a function of the following signature.
basic usage
app.js
var app = ; // 1. include express app path: __dirname + '/models/' connectionString: 'mongodb://localhost/test' debug: true; //if you want to load your controllers,start your app, any other action requiring the models to be loaded/defined// you may listen for the 'mongoose.models.ready' event like so:app;
models/User.js
//an example mongoose model in express-mongoose-helper//your module should export a function like so.//you can customize which arguments are injected, the defaults are shown below.module{ //creates a mongoose model named user and adds it to the express app. app; // now you can access the model like `app.model.User` from your controllers. };
new in version 1.0.7:
- module exports a function called
standalone
for creating a standalone instance without express, useful for background scripts or with other server environments - when constructing models with
app.model()
the model will now be returned. the model will also contain a function you can use to get the mongoose instance. - callback to
app.model()
will now receivemongoose
as a second argument in addition toschema
.
new standalone feature
const standalone = ; const app = ; app;
changes to app.model
const model = app;const mongoose = model;// do something with mongoose
new in version 1.0.2, app.model supports a 4th parameter, schemaOptions
please note, to avoid breaking backwards compatability schemaOptions and callback can be given in either order. both are optional.
module{ app; };
options
//default optionsoptions = connectionString: ''// mongodb connection string connectionOptions: {}// mongodb connection options path: ''// path to folder containing models inject: 'app''types' //arguments to inject into each required model debug: false //show log messages { return thisdebug && consolelog; } //default logging function, can be changed {} //extend mongoose with global plugins, custom types, etc.;
events
several events are emitted. they are listed below.
mongoose.models.ready
= emitted when all the model files have been loaded and added to the app.mongoose.connected
= emitted when database connection is established.mongoose.disconnected
= emitted when database is disconnected.mongoose.error
= emitted when an error occurs establishing connection to mongodb.
testing
No testing is done yet.