Skip to content

omrilitov/mongoose-plugin-seed

Repository files navigation

mongoose-plugin-seed

Mongoose plugin to seed your models

Linux OSX Windows Coverage Dependencies DevDependencies
Coverage Status

Overview

This module will seed your Mongoose models while using dependency management between them. It will empty the collection and create the new given data.

To use:

  1. npm install --save mongoose-plugin-seed
  2. Use the plugin in the desired Models with given seed data
  3. Call seed

Examples

const addSeed = require('mongoose-plugin-seed').addSeed;
const mongooseSeed = require('mongoose-plugin-seed').seed;

// Define Schemas
var UserSchema = new Schema({...});
var RoleSchema = new Schema({...});

// Define Models
var User = mongoose.model('User', UserSchema);
var Role = mongoose.model('Role', RoleSchema);

// Define the seed with dependency to roles
addSeed(User, {
    dependencies: [Role],
    seed: function (roles) {
      return [{
        username: "foo",
        password: "123",
        roles: roles[0]
      }, {
        username: "bar",
        password: "321",
        roles: roles[1]
      }];
    }
  });

// Define roles seed
addSeed(Role, {
    seed: function () {
      return [{
        name: "admin"
      }, {
        name: "user"
      }];
    }
  });

// Seed!
mongooseSeed()
  .then(function () {
    console.log('Success!');
  });

API

addSeed

var addSeed = require('mongoose-plugin-seed').addSeed;
addSeed(Model, options);
  • Model - The mongoose model to seed

The plugin uses the following options:

  • seed - function that returns the seed data (using required dependencies)
  • dependencies (optional) - dependencies to seed the data
  • drop (default=false) - should drop existing collection instead of removing all documents

createSeedModel

var createSeedModel = require('mongoose-plugin-seed').createSeedModel;
createSeedModel(name, Schema, options);
  • name - The name to give to the mongoose model
  • Schema - The mongoose schema to create and seed
  • options - Same options as the addSeed API

This function returns the created model. It is just a short for

var Model = mongoose.model(name, Schema);
addSeed(Model, options);

seed

var mongooseSeed = require('mongoose-plugin-seed').seed;
mongooseSeed();

The function seeds all the data in the correct order. Returns a Promise.

About

Mongoose plugin to seed your models

Resources

License

Stars

Watchers

Forks

Packages

No packages published