MongoDB Database Seeding Library
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
-
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
cause The MongoDB server is not running or is not accessible at the specified URI/port.fixEnsure your MongoDB instance is running. Verify the `database.uri` in your `SeederConfig` or the `MONGO_URI` environment variable is correct and points to an active MongoDB server. -
Error: ENOENT: no such file or directory, scandir '/path/to/nonexistent/data'
cause The path provided to `seeder.readCollectionsFromPath()` does not exist or is incorrect.fixDouble-check the path provided to `readCollectionsFromPath`. Use `path.resolve(__dirname, 'your-data-directory')` to ensure an absolute path is used, especially when running from different working directories. -
TypeError: Cannot read properties of undefined (reading 'insertMany')
cause This often occurs when the database connection is not established correctly or the `mongodb` driver version is incompatible.fixEnsure the `mongodb` driver is installed and compatible with `mongo-seeding`'s version. Check the `database.uri` and `database.options` in your `SeederConfig` for correct connection parameters.
Warnings
- breaking The `collectionInsertManyOptions` property in `SeederConfig` has been removed and replaced with `bulkWriteOptions`. This change aligns with updates in the underlying MongoDB driver's bulk operation handling.
- gotcha When using JavaScript files (`.js`) or TypeScript files (`.ts`) for seed data, ensure that the files export an array of documents as their default export. Non-array exports or incorrect export formats will lead to silent failures or errors during import.
- gotcha The library might not explicitly close the underlying MongoDB client connection after seeding, depending on how it's initialized. In long-running processes or serverless environments, this can lead to open connections.
Install
-
npm install mongo-seeding -
yarn add mongo-seeding -
pnpm add mongo-seeding
Imports
- Seeder
const Seeder = require('mongo-seeding');import { Seeder } from 'mongo-seeding'; - SeederConfig
import { SeederConfig } from 'mongo-seeding';import type { SeederConfig } from 'mongo-seeding'; - DatabaseConfig
import type { DatabaseConfig } from 'mongo-seeding';
Quickstart
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" }
// ]