Mongo Seeding CLI and Library
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
-
TypeError: Cannot read properties of undefined (reading 'collectionInsertManyOptions') or Property 'collectionInsertManyOptions' does not exist on type 'SeederConfig'.
cause Attempting to use `collectionInsertManyOptions` in `SeederConfig` after upgrading to `mongo-seeding` v4.x.fixReplace `collectionInsertManyOptions` with `bulkWriteOptions` in your `SeederConfig` object. -
SyntaxError: Cannot use import statement outside a module or ReferenceError: require is not defined
cause Mixing CommonJS `require()` with ESM `import` statements in Node.js, or trying to use ESM syntax in a non-ESM context (e.g., a `.js` file without `"type": "module"` in `package.json`).fixFor programmatic use, ensure your project is configured for ESM (add `"type": "module"` to `package.json`) and use `import` statements. If using CommonJS, stick to `require()` and ensure the library version supports it, or use a transpiler. -
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 or Unable to connect to MongoDB
cause The MongoDB server is not running, is configured on a different host/port, or network issues are preventing a connection.fixVerify that your MongoDB instance is running and accessible. Check the connection URI/details (host, port, credentials) in your `SeederConfig` or CLI parameters (e.g., `--db-uri`). Ensure no firewall is blocking the connection. Run `docker run --rm -p 27017:27017 mongo` for a quick local MongoDB instance. -
Error: Path to collections is not specified or Error: No collections found in the specified path
cause The path provided to `seeder.readCollectionsFromPath()` is incorrect, empty, or the data files within do not follow the expected structure (e.g., subdirectories for collections, JS/JSON files exporting data).fixDouble-check the `path.resolve()` argument. Ensure your data directory has subdirectories named after your collections (e.g., `./data/users/user-data.js`) and each file exports an array or object of documents.
Warnings
- breaking In `mongo-seeding` v4.0.0, the `collectionInsertManyOptions` property in `SeederConfig` was replaced by `bulkWriteOptions`. This change aligns with updates in the underlying MongoDB driver API.
- gotcha The `mongo-seeding` library and CLI periodically update their supported Node.js versions. For example, v3.7.1 updated to Node 16, and v4.0.2 updated to Node 22.15. Using an older Node.js runtime with newer package versions may lead to compatibility issues or errors.
- gotcha For TypeScript data import files, ensure proper configuration for `ts-node` or a similar transpiler if running directly, or pre-transpile the files. The `--transpile-only` CLI option can improve performance by skipping type checking.
Install
-
npm install mongo-seeding-cli -
yarn add mongo-seeding-cli -
pnpm add mongo-seeding-cli
Imports
- Seeder
const { Seeder } = require('mongo-seeding');import { Seeder } from 'mongo-seeding'; - SeederConfig
import { SeederConfig } from 'mongo-seeding';import type { SeederConfig } from 'mongo-seeding'; - Transformers
import { Transformers } from 'mongo-seeding';import { Seeder } from 'mongo-seeding'; const { replaceDocumentIdWithUnderscoreId, setTimestamps } = Seeder.Transformers;
Quickstart
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();