mongoose-plugin-seed
v0.4.0
Published
Mongoose plugin to seed your models
Downloads
8
Readme
mongoose-plugin-seed
Mongoose plugin to seed your models
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:
npm install --save mongoose-plugin-seed
- Use the plugin in the desired Models with given seed data
- 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 datadrop (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 modelSchema
- The mongoose schema to create and seedoptions
- 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.