Mongo Seeding CLI and Library

4.0.2 · active · verified Wed Apr 22

Mongo Seeding is a versatile tool designed for populating MongoDB databases, offering flexibility through its command-line interface (CLI), a programmatic JavaScript/TypeScript library, and a Docker image. It enables developers to define import data using JavaScript, TypeScript, or JSON files, allowing for dynamic data generation and logic, a key differentiator from simpler tools like `mongoimport` which primarily handle static JSON. The current stable version is 4.0.2, and the project demonstrates an active release cadence with regular maintenance updates and significant version bumps, such as v4.0.0. It is frequently used for setting up development environments, testing database queries, and establishing initial application states.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically seed a MongoDB database using the `mongo-seeding` library in TypeScript, including configuring the seeder, reading data from files, and applying transformers. It also highlights the usage of `bulkWriteOptions` introduced in v4.0.0.

import { Seeder } from 'mongo-seeding';
import path from 'path';

const config = {
  database: 'mongodb://localhost:27017/my-database-test',
  dropDatabase: true, // Be cautious: this will delete the entire database
  dropCollections: true,
  // As of v4.0.0, use bulkWriteOptions instead of collectionInsertManyOptions
  bulkWriteOptions: {
    ordered: false,
  },
};

const seeder = new Seeder(config);
const collections = seeder.readCollectionsFromPath(
  path.resolve(__dirname, './data'),
  {
    transformers: [Seeder.Transformers.replaceDocumentIdWithUnderscoreId],
  },
);

async function seedDatabase() {
  try {
    console.log('Starting database seeding...');
    await seeder.import(collections);
    console.log('Database seeding completed successfully.');
  } catch (err) {
    console.error('Database seeding failed:', err);
    process.exit(1);
  }
}

// Example data structure in a './data/users/users.js' file:
// module.exports = [
//   { id: 'user1', name: 'Alice', email: 'alice@example.com' },
//   { id: 'user2', name: 'Bob', email: 'bob@example.com' },
// ];

seedDatabase();

view raw JSON →