Create Express 4 router and middleware from Mongoose 4 model.
var express = require('express');
var mongoose = require('mongoose');
var router = require('mongoose-express-router');
var db = mongoose.createConnection('mongodb://localhost/test');
var schema = mongoose.Schema({ name: 'string' }).plugin(router);
var User = mongoose.model('User', schema);
var app = express();
app.use('/users', User.router());
app.listen(3000);
You can also use router middleware individually:
app
.get('/users', User.router('find'))
.post('/users', User.router('create'))
.get('/users/:id', User.router('findOne'))
.patch('/users/:id', User.router('update'))
.delete('/users/:id', User.router('delete'));
The following query parameters are recognized:
skip
or offset
limit
sort
select
populate
match
It's often useful to have the session available in mongoose middleware to do things like validation and authorization.
User.pre('find', function (next) {
console.log(this.session);
next();
});
User.pre('save', function (next) {
console.log(this.session);
next();
});
The session is set whenever the router middleware is used, otherwise set the
session
query option.
User.findOne()
.setOptions({ session: req.session })
.exec(function (err, user) {
console.log(user.session === req.session);
// => true
});
You must provide your own body parsing middleware. A req.body
object must be
available for the post/create middleware to work.
Custom middleware can be accessed using Model.router()
and has the model
exposed via req.Model
:
schema.plugin(router, {
middleware: {
myMiddleware: function (req, res, next) {
console.log(req.Model);
next();
}
}
});
// Returns middleware
User.router('myMiddleware');