Seed 5000 data MongoDB data nodejs with faker

Rojan Dhimal
2 min readDec 14, 2022

The easiest way to seed data in MongoDB with node.js and faker. Seed 5000+ data just in 3 steps.

First install required library mongoose and faker.

npm i mongoose faker

Secondly, create two file model.js and seed.js
model.js is to create model schema and seed.js where seeding logic is written.

In model.js place following code or you can create any schema as per your need. here i will create one with two parameter name and price for Product model.

const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
name:{
type:String,
required:true
},
price:{
type:Number,
required:true
}
})
const Product = mongoose.model("Product",productSchema)
module.exports = Product;

In seed.js place following code and replace your mongodb connection uri. Since in our product model there are only two field name and price. Random data for name and price is genereted in loop for 5000 iterations. You can add as many iteration and data based on you requirements.

// require the necessary libraries
const faker = require("faker");
const mongoose = require("mongoose")
const Product = require("./model")

async function seedData() {
// Connection URL
const uri = "mongodb://localhost:27017/database_name";
const seed_count = 5000;
mongoose.set("strictQuery", false);
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log("Connected to db")
}).catch((err) => {
console.log("error", err)
})

let timeSeriesData = [];
// create 5000 fake data
for (let i = 0; i < seed_count; i++) {
const name = faker.name.firstName();
const price = faker.commerce.price()
timeSeriesData.push({ name, price });
}

const seedDB = async () => {
await Product.insertMany(timeSeriesData)
}

seedDB().then(() => {
mongoose.connection.close()
console.log("seed success")
})
}

seedData()

Finally, run command node seed.js on your terminal and wait for some second to seed the data in the database. That’s it you have successfully seed 5000 data in just 3 steps.

github : https://github.com/rojandhimal/rocket-js-tutorials/tree/main/mongodb-seed-data

Youtube Video : https://youtu.be/g4DNe8nBZ_s

--

--