Mongoose - REST - Middleware
Express middleware to create a RESTful API from a mongo database.
Installation
$npm install restfulgoose
Usage
Restfulgoose will expose a mongoose colleciton to an api endpoint. For example, the collection robots
defined by robotSchema
var robotSchema = mongoose;
will respond to the following requests.
Request | Response |
---|---|
GET /api/robots | Get all in collection robots |
GET /api/robots/1 | Get robot with Id 1 |
POST /api/robots | Create a new robot |
PUT /api/robots/1 | Update the robot with Id 1 |
DELETE /api/robots/1 | Delete the robot with Id 1 |
Setup
See example
directory for a working server
var app = ;var mongoose = ;var mongo_rest = ; //set up a mongoose schemavar robotSchema = mongoose; app; app;
Passing in Models
There are two ways to tell restfulgoose about your Mongoose models:
- Pass in Mongoose models directly
- Pass in a url and a schema.
var robotSchema = mongoose;var humanSchema = mongoose;var Robot = mongoose; app;
Authorization
Optionally pass a function to restigoose that will be used for authorization. Authorization functions are passed on a collection by collection basis and are formatted as standard Connect middleware.
Examples using Passport and a custom function for authentication.
//pass an authorization function to the collection//...collections: //... protectedCollection: methods: 'GET' schema: protectedSchema auth: passport //using a passport Basic Authentication strategy secretCollection: methods: 'GET' 'POST' 'PUT' 'DELETE' schema: secretSchema { //using a custom user authentication function if Math > 05 ; //call next if user authorized else res; //handle failed user authentication }
Options
Pass additional options to a collection
collections: robots: methods: 'GET''POST''PUT' 'DELETE' schema: robotSchema path: robotFactory options: sortBy: '-name' //sort by name in descending order selectFields: 'name' 'speed' //only return these fields
Custom Search Functions
Optionally overwrite the function that determines the search query. The serach query takes three arguments, a Mongoose query, a parsed object from the url string, and a request.
robots: methods: 'GET' 'POST' 'PUT' 'DELETE' schema: robotSchema { //for example, a mongoose query could be passed in the request if reqquery queryreqquery; } { //var sortOptions = logic determining sort order //query.sort(sortOptions) } { //var selectFields = logic determing which fields to select //query.find(selectFields) }
URL Querying
Right now, we can use the url to query the collection for matches.
-GET
to /api/robots?name=WallE
returns robots with the name WallE
-GET
to /api/robots?type=vaccuum&speed=3
returns robots of type vacuum whose favorite law is 3