I need to seed data into the database in my application. What is the best way to do that? Where should I write the code for seeding the data? what should be the folder structure for this?
I am a rails developer and rails framework has a nice way of seeding the data in seeds.rb, and I want to achieve the same thing in my node.js application.
Since I am new to node.js, I am confused between different available resources on the web.
First create your model in models folder.
models/product.js
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
image: { type: String, required: true },
title: { type: String, required: true },
author: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true }
});
const Product = mongoose.model("Product", productSchema);
module.exports = Product;
Then create a seeder folder seeder/seedProducts.js
const Product = require("../models/product");
const mongoose = require("mongoose");
const dev = require("../config/dev"); //get your mongoose string
//create your array. i inserted only 1 object here
const products = [
new Product({
image:
"https://static.seattletimes.com/wp-content/uploads/2018/01/a8e801dc-f665-11e7-bf8f-ddd02ba4a187-780x1181.jpg",
title: "Origin",
author: "Dan Brown",
description:
"2017 mystery thriller novel. Dan Brown is back with another thriller so moronic you can feel your IQ points flaking away like dandruff",
price: 12
}),]
//connect mongoose
mongoose
.connect(String(dev.db), { useNewUrlParser: true })
.catch(err => {
console.log(err.stack);
process.exit(1);
})
.then(() => {
console.log("connected to db in development environment");
});
//save your data. this is an async operation
//after you make sure you seeded all the products, disconnect automatically
products.map(async (p, index) => {
await p.save((err, result) => {
if (index === products.length - 1) {
console.log("DONE!");
mongoose.disconnect();
}
});
});
Finally you will run seedProducts.js on the terminal only once.
node seedProducts.js
You can use the mongoose-data-seed package to handle this job.
https://github.com/sharvit/mongoose-data-seed
With mongoose-data-seed you are basically creating seeders files that look like that:
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() {
const usersCount = await User.count().exec();
return usersCount === 0;
}
async run() {
return User.create(data);
}
}
export default UsersSeeder;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With