Seed mongodb with data using mongoose models
npm install --save mongoose-data-seed
md-seed init
md-seed init
will ask you to choose a folder for your seeders and whether to use ES6/2015 syntax which require babel.
md-seed init
will create the seeders
folder, generate md-seed-config.js
and md-seed-generator.json
.
Generate seeder file
md-seed g users
Run all seeders
md-seed run
Or run specific seeders
md-seed run users posts comments
Drop the database before seeding
md-seed run --dropdb
import { Seeder } from "mongoose-data-seed";
import { User } from "../server/models";
const data = [
{
email: "[email protected]",
password: "123123",
password_confirmation: "123123",
isAdmin: true
},
{
email: "[email protected]",
password: "123123",
password_confirmation: "123123",
isAdmin: false
}
];
class UsersSeeder extends Seeder {
async shouldRun() {
return User.countDocuments()
.exec()
.then(count => count === 0);
}
async run() {
return User.create(data);
}
}
export default UsersSeeder;
md-seed
excepting to get 3 values from md-seed-config.js
mongoose
- The mongoose library (somd-seed
will use the same version as your project)mongoURL
- Url to your mongodbseedersList
- A key/value list of all your seeders,md-seed
will run your seeders as they ordered in the list.
import mongooseLib from "mongoose";
mongooseLib.Promise = global.Promise;
import Users from "./seeders/users.seeder";
import Posts from "./seeders/posts.seeder";
import Comments from "./seeders/comments.seeder";
// Export the mongoose lib
export const mongoose = mongooseLib;
// Export the mongodb url
export const mongoURL =
process.env.MONGO_URL || "mongodb://localhost:27017/dbname";
/*
Seeders List
------
order is important
*/
export const seedersList = {
Users,
Posts,
Comments
};
MIT