Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  139] [ 4]  / answers: 1 / hits: 18450  / 7 Years ago, thu, june 8, 2017, 12:00:00

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.


More From » node.js

 Answers
29

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

[#57533] Monday, June 5, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefinap

Total Points: 548
Total Questions: 125
Total Answers: 106

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;