Mongoose

GitHub stars npm version Changelog

feathers-mongoose is a database adapter for Mongoose, an object modeling tool for MongoDB.

$ npm install --save mongoose feathers-mongoose

Important: To use this adapter you also want to be familiar with the database adapter common API and querying mechanism.

This adapter also requires a running MongoDB database server.

API

service(options)

Returns a new service instance initialized with the given options. Model has to be a Mongoose model. See the Mongoose Guide for more information on defining your model.

const mongoose = require('mongoose');
const service = require('feathers-mongoose');

// A module that exports your Mongoose model
const Model = require('./models/message');

// Make Mongoose use the ES6 promise
mongoose.Promise = global.Promise;

// Connect to a local database called `feathers`
mongoose.connect('mongodb://localhost:27017/feathers');

app.use('/messages', service({ Model }));
app.use('/messages', service({ Model, lean, id, events, paginate }));

Options:

  • Model (required) - The Mongoose model definition
  • lean (optional, default: true) - Runs queries faster by returning plain objects instead of Mongoose models.
  • id (optional, default: '_id') - The name of the id field property.
  • events (optional) - A list of custom service events sent by this service
  • paginate (optional) - A pagination object containing a default and max page size
  • discriminators (optional) - A list of mongoose models that inherit from Model.

Important: To avoid odd error handling behaviour, always set mongoose.Promise = global.Promise. If not available already, Feathers comes with a polyfill for native Promises.

Important: When setting lean to false, Mongoose models will be returned which can not be modified unless they are converted to a regular JavaScript object via toObject.

Note: You can get access to the Mongoose model via this.Model inside a hook and use it as usual. See the Mongoose Guide for more information on defining your model.

params.mongoose

When making a service method call, params can contain an mongoose property (for exmaple, {upsert: true}) which allows to modify the options used to run the Mongoose query. Normally this wil be set in a before hook:

app.service('messages').hooks({
  before: {
    patch(hook) {
      // Set some additional Mongoose options
      // The adapter tries to use sane defaults
      // but they can always be changed here
      hook.params.mongoose = {
        runValidators: true,
        setDefaultsOnInsert: true
      }
    }
  }
});

Example

Here's a complete example of a Feathers server with a messages Mongoose service.

$ npm install feathers feathers-errors feathers-rest body-parser mongoose feathers-mongoose

In message-model.js:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const MessageSchema = new Schema({
  text: {
    type: String,
    required: true
  }
});
const Model = mongoose.model('Message', MessageSchema);

module.exports = Model;

Then in app.js:

const feathers = require('feathers');
const errorHandler = require('feathers-errors/handler');
const rest = require('feathers-rest');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const service = require('feathers-mongoose');

const Model = require('./message-model');

// Tell mongoose to use native promises
// See http://mongoosejs.com/docs/promises.html
mongoose.Promise = global.Promise;

// Connect to your MongoDB instance(s)
mongoose.connect('mongodb://localhost:27017/feathers');

// Create a feathers instance.
const app = feathers()
  // Enable REST services
  .configure(rest())
  // Turn on JSON parser for REST services
  .use(bodyParser.json())
  // Turn on URL-encoded parser for REST services
  .use(bodyParser.urlencoded({extended: true}))
  // Connect to the db, create and register a Feathers service.
  .use('/messages', service({
    Model,
    lean: true, // set to false if you want Mongoose documents returned
    paginate: {
      default: 2,
      max: 4
    }
  }))
  .use(errorHandler());

// Create a dummy Message
app.service('messages').create({
  text: 'Message created on server'
}).then(function(message) {
  console.log('Created message', message);
});

// Start the server.
const port = 3030;
app.listen(port, () => {
    console.log(`Feathers server listening on port ${port}`);
});

You can run this example by using node app and go to localhost:3030/messages.

Querying, Validation

Mongoose by default gives you the ability to add validations at the model level. Using an error handler like the one that comes with Feathers your validation errors will be formatted nicely right out of the box!

For more information on querying and validation refer to the Mongoose documentation.

$populate

For Mongoose, the special $populate query parameter can be used to allow Mongoose query population.

app.service('posts').find({
  query: { $populate: 'user' }
});

Discriminators (Inheritance)

Instead of strict inheritance, Mongoose uses discriminators as their schema inheritance model. To use them, pass in a discriminatorKey option to your schema object and use Model.discriminator('modelName', schema) instead of mongoose.model()

Feathers comes with full support for mongoose discriminators, allowing for automatic fetching of inherited types. A typical use case might look like:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Post = require('./post');
var feathers = require('feathers');
var app = feathers();
var service = require('feathers-mongoose');

// Discriminator key, we'll use this later to refer to all text posts
var options = {
  discriminatorKey: '_type'
};

var TextPostSchema = new Schema({
  text: { type: String, default: null }
}, options);

TextPostSchema.index({'updatedAt': -1, background: true});

// Note the use of `Post.discriminator` rather than `mongoose.discriminator`.
var TextPost = Post.discriminator('text', TextPostSchema);

// Using the discriminators option, let feathers know about any inherited models you may have
// for that service
app.use('/posts', service({
  Model: Post,
  discriminators: [TextPost]
}))

Without support for discriminators, when you perform a .get on the posts service, you'd only get back Post models, not TextPost models. Now in your query, you can specify a value for your discriminatorKey:

{
  _type: 'text'
}

and Feathers will automatically swap in the correct model and execute the query it instead of its parent model.

results matching ""

    No results matching ""