1 | ![Mongo Seeding](https://raw.githubusercontent.com/pkosiec/mongo-seeding/main/docs/assets/logo.png)
|
2 |
|
3 | # Mongo Seeding
|
4 |
|
5 | [![npm version](https://badge.fury.io/js/mongo-seeding.svg)](https://npmjs.org/package/mongo-seeding) [![Build Status](https://github.com/pkosiec/mongo-seeding/actions/workflows/branch.yaml/badge.svg)](https://github.com/pkosiec/mongo-seeding/actions) [![codecov](https://codecov.io/gh/pkosiec/mongo-seeding/branch/main/graph/badge.svg?flag=core)](https://codecov.io/gh/pkosiec/mongo-seeding) [![David](https://img.shields.io/david/pkosiec/mongo-seeding.svg?path=core)]() [![David](https://img.shields.io/david/dev/pkosiec/mongo-seeding.svg?path=core)]() [![install size](https://packagephobia.now.sh/badge?p=mongo-seeding)](https://packagephobia.now.sh/result?p=mongo-seeding)
|
6 |
|
7 | The ultimate solution for populating your MongoDB database. Define the data in JavaScript or JSON files. Import collections and documents!
|
8 |
|
9 | ## Table of contents
|
10 |
|
11 |
|
12 |
|
13 | - [Installation](#installation)
|
14 | - [Usage](#usage)
|
15 | - [API description](#api-description)
|
16 | * [`constructor(partialConfig?)`](#constructorpartialconfig)
|
17 | * [`readCollectionsFromPath(path, partialOptions?)`](#readcollectionsfrompathpath-partialoptions)
|
18 | * [`import(collections, partialConfig?)`](#importcollections-partialconfig)
|
19 | - [Debug output](#debug-output)
|
20 |
|
21 |
|
22 |
|
23 | ## Installation
|
24 |
|
25 | To install the app, run the following command:
|
26 |
|
27 | ```bash
|
28 | npm install mongo-seeding --save
|
29 | ```
|
30 |
|
31 | ## Usage
|
32 |
|
33 | 1. Import the `Seeder` class:
|
34 |
|
35 | ```javascript
|
36 | const { Seeder } = require('mongo-seeding');
|
37 | ```
|
38 |
|
39 | 1. Define a partial configuration object. The object will be merged with the default config object (see [Configuration](#configuration) section). Therefore, you can specify only properties, which should override the default values, for example:
|
40 |
|
41 | ```javascript
|
42 | const config = {
|
43 | database: {
|
44 | host: '127.0.0.1',
|
45 | port: 27017,
|
46 | name: 'mydatabase',
|
47 | },
|
48 | dropDatabase: true,
|
49 | };
|
50 | ```
|
51 |
|
52 | Instead of database configuration object, you can also provide database connection URI to the `database` property:
|
53 |
|
54 | ```javascript
|
55 | const config = {
|
56 | database: 'mongodb://127.0.0.1:27017/mydatabase',
|
57 | dropDatabase: true,
|
58 | };
|
59 | ```
|
60 |
|
61 | 1. Instantiate `Seeder` class:
|
62 |
|
63 | ```javascript
|
64 | const seeder = new Seeder(config);
|
65 | ```
|
66 |
|
67 | 1. **(OPTIONAL)** To read MongoDB collections from disk, firstly follow the [tutorial](https://github.com/pkosiec/mongo-seeding/blob/main/docs/import-data-definition.md) in order to define documents and collections to import. Next, read them using `readCollectionsFromPath` method:
|
68 |
|
69 | ```javascript
|
70 | const path = require('path');
|
71 | const collections = seeder.readCollectionsFromPath(path.resolve("./your/path"));
|
72 | ```
|
73 |
|
74 | 1. Seed your database:
|
75 |
|
76 | - with `async/await`, for example:
|
77 |
|
78 | ```javascript
|
79 | try {
|
80 | await seeder.import(collections);
|
81 | } catch (err) {
|
82 | // Handle errors
|
83 | }
|
84 | // Do whatever you want after successful import
|
85 | ```
|
86 |
|
87 | - with raw promises:
|
88 |
|
89 | ```javascript
|
90 | seeder
|
91 | .import(collections)
|
92 | .then(() => {
|
93 | // Do whatever you want after successful import
|
94 | })
|
95 | .catch(err => {
|
96 | // Handle errors
|
97 | });
|
98 | ```
|
99 |
|
100 | See an [**import data example**](https://github.com/pkosiec/mongo-seeding/blob/main/examples/import-data) for a sample Node.js application utilizing the library.
|
101 |
|
102 | ## API description
|
103 |
|
104 | The `Seeder` class contains the following methods.
|
105 |
|
106 | ### `constructor(partialConfig?)`
|
107 |
|
108 | Constructs a new `Seeder` instance and loads configuration for data import.
|
109 |
|
110 | **Configuration**
|
111 |
|
112 | You can override any default configuration property by passing partial config object to the `Seeder` constructor. The object is merged with the default configuration object. To use all default settings, simply omit the constructor argument (`new Seeder()`).
|
113 |
|
114 | The following snippet represents the type definition of `Seeder` config with all available properties:
|
115 |
|
116 | ```typescript
|
117 | export interface SeederConfig {
|
118 | database: string | SeederDatabaseConfigObject; // database connection URI or configuration object
|
119 | databaseReconnectTimeout: number; // maximum time of waiting for successful MongoDB connection in milliseconds. Ignored when `mongoClientOptions` are passed.
|
120 | dropDatabase: boolean; // drops entire database before import
|
121 | dropCollections: boolean; // drops every collection which is being imported
|
122 | mongoClientOptions?: MongoClientOptions; // optional MongoDB connect options
|
123 | collectionInsertManyOptions?: CollectionInsertManyOptions; // optional MongoDB collection import options
|
124 | }
|
125 |
|
126 | export interface SeederDatabaseConfigObject {
|
127 | protocol: string;
|
128 | host: string;
|
129 | port: number;
|
130 | name: string;
|
131 | username?: string;
|
132 | password?: string;
|
133 | options?: SeederDatabaseConfigObjectOptions; // see all options for Database Connection URI: https://docs.mongodb.com/manual/reference/connection-string
|
134 | }
|
135 |
|
136 | export type SeederDatabaseConfigObjectOptions = {
|
137 | [key:string]: string;
|
138 | };
|
139 | ```
|
140 |
|
141 | In order to configure database connection, specify connection URI for `database` property or assign a partial `SeederDatabaseConfigObject` object, overriding necessary properties.
|
142 |
|
143 | **Default configuration**:
|
144 |
|
145 | The default configuration object is as follows:
|
146 |
|
147 | ```javascript
|
148 | const defaultConfig = {
|
149 | database: {
|
150 | protocol: 'mongodb',
|
151 | host: '127.0.0.1',
|
152 | port: 27017,
|
153 | name: 'database',
|
154 | username: undefined,
|
155 | password: undefined,
|
156 | },
|
157 | databaseReconnectTimeout: 10000,
|
158 | dropDatabase: false,
|
159 | dropCollections: false,
|
160 | mongoClientOptions: undefined,
|
161 | collectionInsertManyOptions: undefined;
|
162 | };
|
163 | ```
|
164 |
|
165 | ### `readCollectionsFromPath(path, partialOptions?)`
|
166 |
|
167 | Populates collections and their documents from given path. The path has to contain import data structure described [here](https://github.com/pkosiec/mongo-seeding/blob/main/docs/import-data-definition.md).
|
168 |
|
169 | **Options**
|
170 |
|
171 | You can specify an optional partial options object for this method, which will be merged with default configuration object. See the interface of the options, which describes all possible options:
|
172 |
|
173 | ```typescript
|
174 | export interface SeederCollectionReadingOptions {
|
175 | extensions: string[]; // files that should be imported
|
176 | ejsonParseOptions?: EJSON.Options; // options for parsing EJSON files with `.json` extension
|
177 | transformers: Array<(collection: SeederCollection) => SeederCollection>; // optional transformer functions
|
178 | }
|
179 | ```
|
180 |
|
181 | For example, you may provide the following options object:
|
182 |
|
183 | ```javascript
|
184 | const collectionReadingOptions = {
|
185 | extensions: ['ts', 'js', 'cjs', 'json'],
|
186 | ejsonParseOptions: {
|
187 | relaxed: false,
|
188 | },
|
189 | transformers: [
|
190 | Seeder.Transformers.replaceDocumentIdWithUnderscoreId,
|
191 | ]
|
192 | }
|
193 |
|
194 | const collections = seeder.readCollectionsFromPath(
|
195 | path.resolve('./your/path'),
|
196 | collectionReadingOptions
|
197 | );
|
198 | ```
|
199 |
|
200 | Transform function is a simple function in a form of `(collection: SeederCollection) => SeederCollection`. It means that you can manipulate collections after reading them from disk. `SeederCollection` is defined as follows:
|
201 |
|
202 | ```javascript
|
203 | interface SeederCollection {
|
204 | name: string;
|
205 | documents: object[];
|
206 | }
|
207 | ```
|
208 |
|
209 | There is two built-in transform functions:
|
210 |
|
211 | - **`Seeder.Transformers.replaceDocumentIdWithUnderscoreId`**, which replaces `id` field with `_id` property for every document in collection.
|
212 |
|
213 | - **`Seeder.Transformers.setTimestamps`**, which sets `createdAt` and `updatedAt` timestamps for every document in collection.
|
214 |
|
215 | **Default options**
|
216 |
|
217 | The default options object is as follows:
|
218 |
|
219 | ```javascript
|
220 | const defaultCollectionReadingConfig: SeederCollectionReadingConfig = {
|
221 | extensions: ['json', 'js', 'cjs'],
|
222 | ejsonParseOptions: {
|
223 | relaxed: true,
|
224 | },
|
225 | transformers: [],
|
226 | };
|
227 | ```
|
228 |
|
229 | ### `import(collections, partialConfig?)`
|
230 |
|
231 | This method connects to a database and imports all provided collections. `collections` argument type is an array of `SeederCollection` type, which is defined as follows:
|
232 |
|
233 | ```javascript
|
234 | interface SeederCollection {
|
235 | name: string;
|
236 | documents: object[];
|
237 | }
|
238 | ```
|
239 |
|
240 | **Configuration**
|
241 |
|
242 | You can provide additional `partialConfig` argument in a form of `Seeder` partial configuration object - the same used in the constructor. It is an easy way to change the configuration for one single data import. The configuration object will be merged with provided configuration from constructor and default config.
|
243 |
|
244 | ## Debug output
|
245 |
|
246 | In order to see debug output, set environmental variable `DEBUG` to value `mongo-seeding` before starting your Node.js app:
|
247 |
|
248 | ```bash
|
249 | DEBUG=mongo-seeding node yourapp/index.js
|
250 | ```
|
251 |
|
252 | You can also set it programmatically before requiring `mongo-seeding`:
|
253 |
|
254 | ```javascript
|
255 | process.env.DEBUG = 'mongo-seeding';
|
256 | const { Seeder } = require('mongo-seeding');
|
257 | ```
|