Skip to content

(Updated ) 3 min read Web Dev Written for MongoDB

How to Seed a MongoDB Database with Fake Data

Blog How to seed a MongoDB database with fake data using a Node.js seed script and faker.js, for demos, lookup values and proofs of concept.

Updated : The script now uses @faker-js/faker (the original faker package was deleted in 2022) and the current MongoDB driver, and it waits for the insert to finish before closing the connection.

Corrections
  • : The script closed the client without waiting for insertMany, so it could quit before the insert finished.

TL;DR A quick Node.js script using faker.js to generate thousands of fake documents and insert them into a MongoDB Atlas database. Copy it, tweak the document shape, and you have seed data in seconds.

Have you ever worked on a MongoDB project and needed to seed your database with fake data in order to provide initial values for lookups, demo purposes, proof of concepts, etc.? I’m biased, but I’ve had to seed a MongoDB database countless times.

First of all, what is database seeding? Database seeding is the initial seeding of a database with data. Seeding a database is a process in which an initial set of data is provided to a database when it is being installed.

In this post, you will learn how to get a working seed script setup for MongoDB databases using Node.js and faker.js.

How to Seed MongoDB

This example code uses a single collection of fake IoT data1 (that I used to model for my IoT Kitty Litter Box project). However, you can change the shape of your template document to fit the needs of your application. I am using faker.js to create the fake data. Please refer to the documentation if you want to make any changes. You can also adapt this script to seed data into multiple collections or databases, if needed.

I am saving my data into a MongoDB Atlas database. It’s the easiest way to get a MongoDB database up and running. You’ll need to get your MongoDB connection URI before you can run this script. For information on how to connect your application to MongoDB, check out the docs.

Alright, now that we have got the setup out of the way, let’s jump into the code!

2 We’re a group of engineers who were using Faker in prod when the main package was deleted.The Faker team, January 14, 2022

Install the two packages first: npm install @faker-js/faker mongodb. The original faker package was deleted by its author2 in January 2022; @faker-js/faker is the community fork everyone moved to, and its API is a little different.

2 We’re a group of engineers who were using Faker in prod when the main package was deleted.The Faker team, January 14, 2022
/* mySeedScript.mjs */

import { faker } from '@faker-js/faker';
import { MongoClient } from 'mongodb';

function randomIntFromInterval(min, max) {
	// min and max included
	return Math.floor(Math.random() * (max - min + 1) + min);
}

async function seedDB() {
	// Connection URL
	const uri = 'YOUR MONGODB ATLAS URI';
	const client = new MongoClient(uri);

	try {
		await client.connect();
		console.log('Connected correctly to server');

		const collection = client.db('iot').collection('kitty-litter-time-series');

		// deleteMany({}) destroys all data in the collection.
		// Make sure you run it against the right database and collection.
		await collection.deleteMany({});

		// make a bunch of time series data
		const timeSeriesData = [];

		for (let i = 0; i < 5000; i++) {
			const firstName = faker.person.firstName();
			const lastName = faker.person.lastName();
			const newDay = {
				timestamp_day: faker.date.past(),
				cat: faker.animal.cat(),
				owner: {
					email: faker.internet.email({ firstName, lastName }),
					firstName,
					lastName,
				},
				events: [],
			};

			for (let j = 0; j < randomIntFromInterval(1, 6); j++) {
				newDay.events.push({
					timestamp_event: faker.date.past(),
					weight: randomIntFromInterval(14, 16),
				});
			}
			timeSeriesData.push(newDay);
		}
		await collection.insertMany(timeSeriesData);

		console.log('Database seeded! :)');
	} catch (err) {
		console.log(err.stack);
	} finally {
		await client.close();
	}
}

seedDB();

Run it with node mySeedScript.mjs.

After running the script above, be sure to check out your database to ensure that your data has been properly seeded. This is what my database looks like after running the script above.

Screenshot showing the seeded data in a MongoDB Atlas cluster.
Screenshot showing the seeded data in a MongoDB Atlas cluster.

Once your fake seed data is in the MongoDB database, you’re done! Congratulations! If you want a nice way to browse and verify your seeded data, I’d recommend the MongoDB Visual Studio Code pluginOct 20, 2020How To Use The MongoDB Visual Studio Code Plugin for exploring your collections right from your editor.

More Technical Posts

Works on My Machine

Get the next post by email. My newsletter covers homelab builds, AI tools and open source, and it goes out when I have something to say.

It’s free, and you can unsubscribe anytime. You’ll get an email to confirm first.

If you liked this post, consider sharing it on Hacker News, Bluesky, LinkedIn, or X.

Joe Karlsson at his desk, chin on hand, with a microphone in front of him

Joe Karlsson

Technology is better when it's weird and it's yours. Everything I write about runs in my house.

More about me →

BlueskyLinkedInGitHub