MongoDB Database Seeding Library

4.0.2 · active · verified Wed Apr 22

mongo-seeding is a Node.js library specifically designed to populate MongoDB databases with initial data, serving critical roles in development, testing, and creating demo environments. It offers flexibility in data definition, supporting various formats like JSON files and custom JavaScript/TypeScript scripts, and provides granular control over the data insertion process. The library is currently in its active development phase, with version 4.0.2 being the latest stable release as of recent updates. Its release cadence typically involves regular maintenance updates addressing dependencies and minor bug fixes, alongside significant major version increments that introduce breaking changes and new features. A key differentiator for `mongo-seeding` is its declarative approach to defining seed data, comprehensive support for both programmatic API usage and a command-line interface (CLI), and robust error handling mechanisms during data insertion, which collectively make it a reliable and efficient solution for managing and initializing MongoDB database states.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `mongo-seeding`, configure the database connection, read seed data from a directory, and import it into MongoDB. It includes handling potential errors during the seeding process.

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

const MONGO_URI = process.env.MONGO_URI ?? 'mongodb://localhost:27017/my-database';

const config = {
  database: {
    uri: MONGO_URI,
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    },
  },
  dropDatabase: true, // Clears the database before seeding
  bulkWriteOptions: {
    ordered: true,
    // writeConcern: { w: 'majority' }
  }
};

const seeder = new Seeder(config);

const collections = seeder.readCollectionsFromPath(
  path.resolve(__dirname, 'data'), // Assuming 'data' directory contains JSON/JS files
  {
    extensions: ['json', 'js', 'ts'],
  },
);

async function seedDatabase() {
  try {
    await seeder.import(collections);
    console.log('Database seeded successfully!');
  } catch (err) {
    console.error('Error seeding database:', err);
  } finally {
    // The Seeder class doesn't expose a direct close method for the client.
    // In a real application, ensure the underlying MongoClient is closed if managed externally.
  }
}

seedDatabase();

// Example content for 'data/users.json':
// [
//   { "name": "Alice", "email": "alice@example.com" },
//   { "name": "Bob", "email": "bob@example.com" }
// ]

view raw JSON →