{"id":16447,"library":"mongo-seeding","title":"MongoDB Database Seeding Library","description":"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.","status":"active","version":"4.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/pkosiec/mongo-seeding","tags":["javascript","mongo","mongodb","seed","db-seed","database","seeding","db","ejson"],"install":[{"cmd":"npm install mongo-seeding","lang":"bash","label":"npm"},{"cmd":"yarn add mongo-seeding","lang":"bash","label":"yarn"},{"cmd":"pnpm add mongo-seeding","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime dependency for connecting to MongoDB and utilizing its driver options (e.g., MongoClientOptions, bulkWriteOptions).","package":"mongodb","optional":false}],"imports":[{"note":"The library primarily uses ES modules. For CommonJS, dynamic import or specific transpilation settings might be required, though direct `require` is not recommended for modern usage.","wrong":"const Seeder = require('mongo-seeding');","symbol":"Seeder","correct":"import { Seeder } from 'mongo-seeding';"},{"note":"Used as a type for configuration options. Use `import type` for type-only imports to prevent bundling issues and improve tree-shaking.","wrong":"import { SeederConfig } from 'mongo-seeding';","symbol":"SeederConfig","correct":"import type { SeederConfig } from 'mongo-seeding';"},{"note":"A type definition for database connection settings, useful when defining the `database` property within `SeederConfig`.","symbol":"DatabaseConfig","correct":"import type { DatabaseConfig } from 'mongo-seeding';"}],"quickstart":{"code":"import { Seeder } from 'mongo-seeding';\nimport path from 'path';\n\nconst MONGO_URI = process.env.MONGO_URI ?? 'mongodb://localhost:27017/my-database';\n\nconst config = {\n  database: {\n    uri: MONGO_URI,\n    options: {\n      useNewUrlParser: true,\n      useUnifiedTopology: true,\n    },\n  },\n  dropDatabase: true, // Clears the database before seeding\n  bulkWriteOptions: {\n    ordered: true,\n    // writeConcern: { w: 'majority' }\n  }\n};\n\nconst seeder = new Seeder(config);\n\nconst collections = seeder.readCollectionsFromPath(\n  path.resolve(__dirname, 'data'), // Assuming 'data' directory contains JSON/JS files\n  {\n    extensions: ['json', 'js', 'ts'],\n  },\n);\n\nasync function seedDatabase() {\n  try {\n    await seeder.import(collections);\n    console.log('Database seeded successfully!');\n  } catch (err) {\n    console.error('Error seeding database:', err);\n  } finally {\n    // The Seeder class doesn't expose a direct close method for the client.\n    // In a real application, ensure the underlying MongoClient is closed if managed externally.\n  }\n}\n\nseedDatabase();\n\n// Example content for 'data/users.json':\n// [\n//   { \"name\": \"Alice\", \"email\": \"alice@example.com\" },\n//   { \"name\": \"Bob\", \"email\": \"bob@example.com\" }\n// ]","lang":"typescript","description":"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."},"warnings":[{"fix":"Update your `SeederConfig` to use `bulkWriteOptions` instead of `collectionInsertManyOptions`. For example, `bulkWriteOptions: { ordered: true }` replaces `collectionInsertManyOptions: { ordered: true }`.","message":"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.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Verify that your seed data files (e.g., `users.js`) contain a `export default [...]` where `...` is an array of MongoDB documents.","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Ensure you manage the MongoDB client lifecycle externally if necessary. If `mongo-seeding` creates the client internally, there might not be a direct method to close it via the `Seeder` instance. Consider explicitly connecting and passing an `MongoClient` instance to the seeder's config if fine-grained control is needed.","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure 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.","cause":"The MongoDB server is not running or is not accessible at the specified URI/port.","error":"MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017"},{"fix":"Double-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.","cause":"The path provided to `seeder.readCollectionsFromPath()` does not exist or is incorrect.","error":"Error: ENOENT: no such file or directory, scandir '/path/to/nonexistent/data'"},{"fix":"Ensure 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.","cause":"This often occurs when the database connection is not established correctly or the `mongodb` driver version is incompatible.","error":"TypeError: Cannot read properties of undefined (reading 'insertMany')"}],"ecosystem":"npm"}