Seeding Data With Node.js Scripts
Learners will write a Node.js seed script that reads a JSON file and bulk-inserts documents into MongoDB for local development.
Why Write a Seed Script?
A seed script is a Node.js program that populates a MongoDB database with initial or test data. Unlike mongoimport, a seed script can generate dynamic data (IDs, relationships, timestamps), conditionally insert data that doesn't already exist, and apply business logic while seeding—for example, hashing passwords or computing derived fields. Seed scripts are the backbone of local development environment setup.
Setting Up the MongoDB Client
A seed script connects to MongoDB using the official mongodb Node.js driver. Keep the connection URI in an environment variable or a .env file—never hardcode credentials. Call client.connect() at the start, run all seed operations, and call client.close() in a finally block to ensure the script exits cleanly even if an error occurs.
const { MongoClient, ObjectId } = require('mongodb');
const URI = process.env.MONGO_URI || 'mongodb://localhost:27017';
const DB_NAME = 'myapp';
async function seed() {
const client = new MongoClient(URI);
try {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db(DB_NAME);
await seedUsers(db);
await seedProducts(db);
console.log('Seeding complete!');
} finally {
await client.close();
}
}
seed().catch(console.error);All lessons in this course
- mongoimport: Loading JSON and CSV Files
- mongoexport: Dumping Collections to Files
- mongodump and mongorestore for Full Backups
- Seeding Data With Node.js Scripts