Mongoose plugin to seed your models
Linux | OSX | Windows | Coverage | Dependencies | DevDependencies |
---|---|---|---|---|---|
This module will seed your Mongoose models while using dependency management between them. It will empty the collection and create the new given data.
npm install --save mongoose-plugin-seed
- Use the plugin in the desired Models with given seed data
- Call seed
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!');
});
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
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);
var mongooseSeed = require('mongoose-plugin-seed').seed;
mongooseSeed();
The function seeds all the data in the correct order. Returns a Promise.