nongo-driver 3.3.5 → 3.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/model.ts CHANGED
@@ -1,5 +1,21 @@
1
1
  import clone from 'clone-deep';
2
- import {AggregateOptions, AnyBulkWriteOperation, BulkWriteOptions, BulkWriteResult, CountDocumentsOptions, Db, DeleteOptions, DeleteResult, Document, Filter, FindOptions, ObjectId, UpdateFilter, UpdateOptions, UpdateResult} from 'mongodb';
2
+ import {
3
+ AggregateOptions,
4
+ AnyBulkWriteOperation,
5
+ BulkWriteOptions,
6
+ BulkWriteResult,
7
+ CountDocumentsOptions,
8
+ Db,
9
+ DeleteOptions,
10
+ DeleteResult,
11
+ Document,
12
+ Filter,
13
+ FindOptions,
14
+ ObjectId,
15
+ UpdateFilter,
16
+ UpdateOptions,
17
+ UpdateResult,
18
+ } from 'mongodb';
3
19
  import {diff} from 'just-diff';
4
20
  import semverGt from 'semver/functions/gt';
5
21
  import incVersion from 'semver/functions/inc';
@@ -10,14 +26,14 @@ import MongoIndex from './mongo-index';
10
26
  import Nongo from './nongo';
11
27
  import Validator from './validator';
12
28
 
13
- const DEFAULT_PATHS = ['_id', 'revision', 'history', 'diffs']
29
+ const DEFAULT_PATHS = ['_id', 'revision', 'history', 'diffs'];
14
30
 
15
31
  function excludePathsFromDiff(diff, excludedPaths = DEFAULT_PATHS) {
16
32
  return diff.filter((d) => {
17
33
  if (!excludedPaths.includes(d.path[0])) {
18
34
  return true;
19
35
  }
20
- })
36
+ });
21
37
  }
22
38
 
23
39
  export interface RevisionHistory {
@@ -26,7 +42,18 @@ export interface RevisionHistory {
26
42
  created?: Date;
27
43
  }
28
44
 
29
- export default abstract class Model<T extends {_id?: ObjectId, revision?: string, history?: RevisionHistory[], diffs?: any, name?: string, environment?: string, deleted?:true} = any> {
45
+ export default abstract class Model<
46
+ T extends {
47
+ _id?: ObjectId;
48
+ revision?: string;
49
+ history?: RevisionHistory[];
50
+ diffs?: any;
51
+ name?: string;
52
+ key?: string;
53
+ environment?: string;
54
+ deleted?: true;
55
+ } = any,
56
+ > {
30
57
  // {@code instanceof} can be a bit funny when importing classes across
31
58
  // modules so this is an explicit type guard we can use
32
59
  public isNongoModel: true = true;
@@ -50,15 +77,19 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
50
77
 
51
78
  this.collection = this.defineCollection();
52
79
  this.collectionRevision = // e.g. BlockRevision
53
- this.schemaVersioningEnabled() ? `${this.defineCollection()}${Nongo.REVISION}` : null;
80
+ this.schemaVersioningEnabled()
81
+ ? `${this.defineCollection()}${Nongo.REVISION}`
82
+ : null;
54
83
  this.collectionEnvironmentMapping = // e.g. BlockEnvironmentMapping
55
- this.schemaVersioningEnabled() ? `${this.defineCollection()}${Nongo.ENVIRONMENT_MAPPING}` : null;
84
+ this.schemaVersioningEnabled()
85
+ ? `${this.defineCollection()}${Nongo.ENVIRONMENT_MAPPING}`
86
+ : null;
56
87
  this.name = this.constructor.name;
57
88
  this.dynamic = false;
58
89
  this.initStructure();
59
90
  }
60
91
 
61
- public getCollectionRevision (): string {
92
+ public getCollectionRevision(): string {
62
93
  return this.collectionRevision;
63
94
  }
64
95
 
@@ -84,17 +115,22 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
84
115
  }
85
116
 
86
117
  private async getLatestRevisionNumber(name: string): Promise<string> {
87
- const liveObj = await this.db.collection(this.collection).findOne({name}, {sort:{revision: -1}});
88
- const revObj = await this.db.collection(this.collectionRevision).findOne({name}, {sort:{revision: -1}});
89
- let version = "0.0.1";
118
+ const query = this.collection === 'FormModel' ? {key: name} : {name};
119
+ const liveObj = await this.db
120
+ .collection(this.collection)
121
+ .findOne(query, {sort: {revision: -1}});
122
+ const revObj = await this.db
123
+ .collection(this.collectionRevision)
124
+ .findOne(query, {sort: {revision: -1}});
125
+ let version = '0.0.1';
90
126
  if (liveObj && revObj) {
91
- semverGt(liveObj.revision, revObj.revision) ?
92
- version = incVersion(liveObj.revision, 'patch') :
93
- version = incVersion(revObj.revision, 'patch');
127
+ semverGt(liveObj.revision, revObj.revision)
128
+ ? (version = incVersion(liveObj.revision, 'patch'))
129
+ : (version = incVersion(revObj.revision, 'patch'));
94
130
  } else if (liveObj) {
95
- version = incVersion(liveObj.revision, 'patch')
131
+ version = incVersion(liveObj.revision, 'patch');
96
132
  } else if (revObj) {
97
- version = incVersion(revObj.revision, 'patch')
133
+ version = incVersion(revObj.revision, 'patch');
98
134
  }
99
135
  return version;
100
136
  }
@@ -118,51 +154,72 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
118
154
  this.throwValidationError(err);
119
155
  }
120
156
  }
121
-
157
+
122
158
  if (this.collectionRevision) {
123
- const query = ObjectId.isValid(this.obj.environment) ? {_id: new ObjectId(this.obj.environment)} : {isLive:true}
159
+ const query = ObjectId.isValid(this.obj.environment)
160
+ ? {_id: new ObjectId(this.obj.environment)}
161
+ : {isLive: true};
124
162
  const clientEnv = await this.db.collection('Environment').findOne(query);
125
163
  const environmentId = clientEnv._id.toHexString();
126
164
 
127
- const {name} = this.obj;
128
- this.obj.revision = await this.getLatestRevisionNumber(name);
165
+ const {name, key} = this.obj;
166
+ this.obj.revision = await this.getLatestRevisionNumber(name || key);
129
167
 
130
168
  if (clientEnv.isLive) {
131
169
  const revisionObjId = new ObjectId();
132
- const liveRevisionObject = await this.db.collection(this.collection).findOne({_id: this.obj._id});
133
- this.obj.history = Nongo.revisionHistory(liveRevisionObject, revisionObjId);
170
+ const liveRevisionObject = await this.db
171
+ .collection(this.collection)
172
+ .findOne({_id: this.obj._id});
173
+ this.obj.history = Nongo.revisionHistory(
174
+ liveRevisionObject,
175
+ revisionObjId,
176
+ );
134
177
  await this.db
135
178
  .collection(this.collection)
136
179
  .replaceOne({_id: this.obj._id}, this.obj, {upsert: true});
137
180
  if (liveRevisionObject) {
138
181
  liveRevisionObject._id = revisionObjId;
139
- await this.db.collection(this.collectionRevision).insertOne(liveRevisionObject);
182
+ await this.db
183
+ .collection(this.collectionRevision)
184
+ .insertOne(liveRevisionObject);
140
185
  }
141
186
  } else {
142
- const revisionObj = await this.db.collection(this.collectionRevision).findOne({_id: this.obj._id});
143
-
187
+ const revisionObj = await this.db
188
+ .collection(this.collectionRevision)
189
+ .findOne({_id: this.obj._id});
190
+
144
191
  this.obj.history = Nongo.revisionHistory(revisionObj, this.idString());
145
192
  this.obj._id = new ObjectId();
146
- const r = await this.db.collection(this.collectionRevision).insertOne(this.obj);
147
- if (this.obj.revision !== "0.0.1") {
193
+ const r = await this.db
194
+ .collection(this.collectionRevision)
195
+ .insertOne(this.obj);
196
+ if (this.obj.revision !== '0.0.1') {
148
197
  // update relevant mappings
149
198
  const revisionId = revisionObj._id.toHexString();
150
199
  const insertedId = r.insertedId.toHexString();
151
- await this.updateEnvironmentMapping(revisionId, insertedId, environmentId);
152
- await this.updateIntentEntityBlockMapping(revisionId, insertedId, environmentId);
200
+ await this.updateEnvironmentMapping(
201
+ revisionId,
202
+ insertedId,
203
+ environmentId,
204
+ );
205
+ await this.updateIntentEntityBlockMapping(
206
+ revisionId,
207
+ insertedId,
208
+ environmentId,
209
+ );
153
210
  }
154
211
  }
155
- if (this.obj.revision === "0.0.1") {
212
+ if (this.obj.revision === '0.0.1') {
156
213
  await this.createEnvironmentMapping(environmentId);
157
214
  }
158
215
  if (this.obj.deleted) {
159
- await this.removeEnvironmentMapping(environmentId)
216
+ await this.removeEnvironmentMapping(environmentId);
160
217
  }
161
218
  } else {
162
219
  // Upsert non revision models
163
220
  await this.db
164
- .collection(this.collection)
165
- .replaceOne({_id: this.obj._id}, this.obj, {upsert: true});
221
+ .collection(this.collection)
222
+ .replaceOne({_id: this.obj._id}, this.obj, {upsert: true});
166
223
  }
167
224
 
168
225
  // Return the saved model
@@ -171,45 +228,53 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
171
228
 
172
229
  private async removeEnvironmentMapping(environmentId: string): Promise<void> {
173
230
  const path = `environments.${environmentId}`;
174
- await this.db.collection(this.collectionEnvironmentMapping).updateOne(
175
- {originalId: this.idString()},
176
- {$unset: {[path]: ""}}
177
- )
231
+ await this.db
232
+ .collection(this.collectionEnvironmentMapping)
233
+ .updateOne({originalId: this.idString()}, {$unset: {[path]: ''}});
178
234
  }
179
235
 
180
236
  private async createEnvironmentMapping(environmentId: string): Promise<void> {
181
237
  await this.db.collection(this.collectionEnvironmentMapping).insertOne({
182
238
  originalId: this.idString(),
183
- environments: {[environmentId]: this.idString()}
184
- })
239
+ environments: {[environmentId]: this.idString()},
240
+ });
185
241
  }
186
242
 
187
- private async updateEnvironmentMapping(revisionId: string, insertedId: string, environmentId: string): Promise<void> {
188
- const path = `environments.${environmentId}`
189
- await this.db.collection(this.collectionEnvironmentMapping).updateOne(
190
- {[path]: revisionId},
191
- { $set: {[path]: insertedId}}
192
- )
243
+ private async updateEnvironmentMapping(
244
+ revisionId: string,
245
+ insertedId: string,
246
+ environmentId: string,
247
+ ): Promise<void> {
248
+ const path = `environments.${environmentId}`;
249
+ await this.db
250
+ .collection(this.collectionEnvironmentMapping)
251
+ .updateOne({[path]: revisionId}, {$set: {[path]: insertedId}});
193
252
  }
194
253
 
195
- private async updateIntentEntityBlockMapping(oldId: string, newId: string, environment: string): Promise<void> {
196
- if (this.collection === "Block") {
254
+ private async updateIntentEntityBlockMapping(
255
+ oldId: string,
256
+ newId: string,
257
+ environment: string,
258
+ ): Promise<void> {
259
+ if (this.collection === 'Block') {
197
260
  // update intent and entity mappings
198
- const filter = {block_id: oldId, environment}
199
- const update = {$set: {'block_id': newId}}
261
+ const filter = {block_id: oldId, environment};
262
+ const update = {$set: {block_id: newId}};
200
263
  await this.db.collection('IntentBlockMapping').updateMany(filter, update);
201
264
  await this.db.collection('EntityBlockMapping').updateMany(filter, update);
202
- } else if (this.collection === "Intent") {
265
+ } else if (this.collection === 'Intent') {
203
266
  // update intent mapping
204
- const filter = {intent_id: oldId, environment}
205
- const update = {$set: {'intent_id': newId}}
267
+ const filter = {intent_id: oldId, environment};
268
+ const update = {$set: {intent_id: newId}};
206
269
  await this.db.collection('IntentBlockMapping').updateMany(filter, update);
207
- } else if (this.collection === "Entity") {
270
+ } else if (this.collection === 'Entity') {
208
271
  // update entity mapping
209
- const filter = {entity_id: oldId, environment}
210
- const update = {$set: {'entity_id': newId}}
272
+ const filter = {entity_id: oldId, environment};
273
+ const update = {$set: {entity_id: newId}};
211
274
  await this.db.collection('EntityBlockMapping').updateMany(filter, update);
212
- } else {
275
+ } else if (this.collection === 'FormModel') {
276
+ return;
277
+ } else {
213
278
  throw Error(`${this.collection} is unsupported revision type.`);
214
279
  }
215
280
  }
@@ -217,12 +282,16 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
217
282
  public async revertVersion(id: string, revisionId: string): Promise<this> {
218
283
  const revisionObjId = new ObjectId();
219
284
  // get the actuall object
220
- const obj = await this.db.collection(this.collection).findOne({_id: new ObjectId(id)});
221
-
285
+ const obj = await this.db
286
+ .collection(this.collection)
287
+ .findOne({_id: new ObjectId(id)});
288
+
222
289
  // get revision
223
- const objToRevert = await this.db.collection(this.collectionRevision).findOne({_id: new ObjectId(revisionId)});
290
+ const objToRevert = await this.db
291
+ .collection(this.collectionRevision)
292
+ .findOne({_id: new ObjectId(revisionId)});
224
293
 
225
- // update revision object
294
+ // update revision object
226
295
  objToRevert.revision = Nongo.revisionNumber(obj.revision);
227
296
  objToRevert.history = Nongo.revisionHistory(obj, revisionObjId);
228
297
  delete objToRevert.diffs;
@@ -234,7 +303,6 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
234
303
  .collection(this.collection)
235
304
  .replaceOne({_id: obj._id}, objToRevert);
236
305
 
237
-
238
306
  // make actuall object as revision object and save it to the revision collection
239
307
  obj._id = revisionObjId;
240
308
  await this.db.collection(this.collectionRevision).insertOne(obj);
@@ -244,7 +312,10 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
244
312
  return new this.constructor(this.nongo, objToRevert);
245
313
  }
246
314
 
247
- public async getRevisionObjForEnvironment(isLive: boolean, id: string): Promise<this> {
315
+ public async getRevisionObjForEnvironment(
316
+ isLive: boolean,
317
+ id: string,
318
+ ): Promise<this> {
248
319
  let doc;
249
320
  const _id = new ObjectId(id);
250
321
 
@@ -264,8 +335,13 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
264
335
  return new this.constructor(this.nongo, doc);
265
336
  }
266
337
 
267
- public async saveEnvironmentRevision(id: string, environmentId: string): Promise<this> {
268
- const obj = await this.db.collection(this.collection).findOne({_id: new ObjectId(id)});
338
+ public async saveEnvironmentRevision(
339
+ id: string,
340
+ environmentId: string,
341
+ ): Promise<this> {
342
+ const obj = await this.db
343
+ .collection(this.collection)
344
+ .findOne({_id: new ObjectId(id)});
269
345
 
270
346
  const revisionObj = clone(obj);
271
347
  revisionObj._id = new ObjectId();
@@ -277,8 +353,12 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
277
353
  return new this.constructor(this.nongo, revisionObj);
278
354
  }
279
355
 
280
- public async removeEnvironmentRevisions(environmentId: string): Promise<DeleteResult> {
281
- const result = await this.db.collection(this.collectionRevision).deleteMany({environment: environmentId})
356
+ public async removeEnvironmentRevisions(
357
+ environmentId: string,
358
+ ): Promise<DeleteResult> {
359
+ const result = await this.db
360
+ .collection(this.collectionRevision)
361
+ .deleteMany({environment: environmentId});
282
362
  return result;
283
363
  }
284
364
 
@@ -351,17 +431,30 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
351
431
  return this.findOne({_id: id});
352
432
  }
353
433
 
354
- public async getRevisionHistory (history: RevisionHistory[]) {
355
- const revisionIds = history.map(i => new ObjectId(i.id));
356
- return this.toArray(await this.findIterator({_id: {$in: revisionIds}}, {sort: {revision: 'descending'}}, this.collectionRevision));
434
+ public async getRevisionHistory(history: RevisionHistory[]) {
435
+ const revisionIds = history.map((i) => new ObjectId(i.id));
436
+ return this.toArray(
437
+ await this.findIterator(
438
+ {_id: {$in: revisionIds}},
439
+ {sort: {revision: 'descending'}},
440
+ this.collectionRevision,
441
+ ),
442
+ );
357
443
  }
358
444
 
359
- public async getRevisions(query: Filter<Document>, options?: FindOptions<Document>): Promise<this[]> {
360
- return this.toArray(await this.findIterator(query, options, this.collectionRevision));
445
+ public async getRevisions(
446
+ query: Filter<Document>,
447
+ options?: FindOptions<Document>,
448
+ ): Promise<this[]> {
449
+ return this.toArray(
450
+ await this.findIterator(query, options, this.collectionRevision),
451
+ );
361
452
  }
362
453
 
363
- public async getRevision (query: Filter<Document>): Promise<this> {
364
- const doc = await this.db.collection(this.collectionRevision).findOne(query);
454
+ public async getRevision(query: Filter<Document>): Promise<this> {
455
+ const doc = await this.db
456
+ .collection(this.collectionRevision)
457
+ .findOne(query);
365
458
 
366
459
  // Return null if no doc was found
367
460
  if (doc == null) {
@@ -378,7 +471,10 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
378
471
  * @param options: the query options e.g. sorting, limiting results etc.
379
472
  * @return the results of the query as an array of models.
380
473
  */
381
- public async find(query: Filter<Document> = {}, options?: FindOptions<Document>): Promise<this[]> {
474
+ public async find(
475
+ query: Filter<Document> = {},
476
+ options?: FindOptions<Document>,
477
+ ): Promise<this[]> {
382
478
  return this.toArray(await this.findIterator(query, options));
383
479
  }
384
480
 
@@ -398,7 +494,7 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
398
494
  * @param options: the query options e.g. sorting, limiting results etc.
399
495
  * @return the results of the query as an {@link AsyncIterator}.
400
496
  */
401
- public async findIterator(
497
+ public async findIterator(
402
498
  query: Filter<Document> = {},
403
499
  options?: FindOptions<Document>,
404
500
  collection = this.collection,
@@ -407,7 +503,7 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
407
503
  const cursor = this.db.collection(collection).find(query, options);
408
504
  return new CursorIterator<this>(
409
505
  cursor,
410
- // @ts-ignore
506
+ // @ts-ignore
411
507
  (obj) => new this.constructor(this.nongo, obj),
412
508
  );
413
509
  }
@@ -430,12 +526,18 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
430
526
  return new this.constructor(this.nongo, doc);
431
527
  }
432
528
 
433
- public async remove(query: Filter<Document>, options?: DeleteOptions): Promise<DeleteResult> {
529
+ public async remove(
530
+ query: Filter<Document>,
531
+ options?: DeleteOptions,
532
+ ): Promise<DeleteResult> {
434
533
  query = this.prepareQuery(query);
435
534
  return this.db.collection(this.collection).deleteMany(query, options);
436
535
  }
437
536
 
438
- public async aggregate(pipeline: Document[], options?: AggregateOptions): Promise<any[]> {
537
+ public async aggregate(
538
+ pipeline: Document[],
539
+ options?: AggregateOptions,
540
+ ): Promise<any[]> {
439
541
  return this.toArray(await this.aggregateIterator(pipeline, options));
440
542
  }
441
543
 
@@ -458,14 +560,21 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
458
560
  return this.db.collection(this.collection).distinct(field, filter);
459
561
  }
460
562
 
461
- public async update(query: Filter<Document>, updates: UpdateFilter<Document>, options?: UpdateOptions): Promise<UpdateResult<Document>> {
563
+ public async update(
564
+ query: Filter<Document>,
565
+ updates: UpdateFilter<Document>,
566
+ options?: UpdateOptions,
567
+ ): Promise<UpdateResult<Document>> {
462
568
  query = this.prepareQuery(query);
463
569
  return this.db
464
570
  .collection(this.collection)
465
571
  .updateMany(query, updates, options);
466
572
  }
467
573
 
468
- public async count(query: Document = {}, options?: CountDocumentsOptions): Promise<number> {
574
+ public async count(
575
+ query: Document = {},
576
+ options?: CountDocumentsOptions,
577
+ ): Promise<number> {
469
578
  return this.db.collection(this.collection).countDocuments(query, options);
470
579
  }
471
580
 
@@ -494,7 +603,9 @@ export default abstract class Model<T extends {_id?: ObjectId, revision?: string
494
603
  if (typeof _id === 'string') {
495
604
  query._id = Nongo.toObjectId(query._id);
496
605
  } else if (_id.$in) {
497
- _id.$in = _id.$in.map((el) => typeof el === 'string' ? Nongo.toObjectId(el) : el);
606
+ _id.$in = _id.$in.map((el) =>
607
+ typeof el === 'string' ? Nongo.toObjectId(el) : el,
608
+ );
498
609
  }
499
610
 
500
611
  return query;
package/src/nongo.ts CHANGED
@@ -4,7 +4,7 @@ import Logger from 'wbb-logger';
4
4
  import incVersion from 'semver/functions/inc';
5
5
  import AtlasApi from './atlas-api';
6
6
  import {Newable} from './interface';
7
- import Model, { RevisionHistory } from './model';
7
+ import Model, {RevisionHistory} from './model';
8
8
  import MongoIndex from './mongo-index';
9
9
  import MongoIndexSet from './mongo-index-set';
10
10
  import NongoParams from './nongo-params';
@@ -42,13 +42,11 @@ export default class Nongo {
42
42
  } else {
43
43
  // we don't want to mutate the original array
44
44
  const array = [...model.history];
45
- array.push(
46
- {
47
- id: revisionId.toString(),
48
- revision: model.revision,
49
- created: new Date(),
50
- }
51
- )
45
+ array.push({
46
+ id: revisionId.toString(),
47
+ revision: model.revision,
48
+ created: new Date(),
49
+ });
52
50
  return array;
53
51
  }
54
52
  }
@@ -58,8 +56,8 @@ export default class Nongo {
58
56
  public noStripKeys: any = {};
59
57
  public db: Db;
60
58
  public dbName: string;
61
- public static REVISION = "Revision";
62
- public static ENVIRONMENT_MAPPING = "EnvironmentMapping";
59
+ public static REVISION = 'Revision';
60
+ public static ENVIRONMENT_MAPPING = 'EnvironmentMapping';
63
61
 
64
62
  // Parallel to {@code this.modelClasses} and {@code this.schemaParsers}
65
63
  private instances: Model[];
@@ -82,12 +80,15 @@ export default class Nongo {
82
80
  public schemaParsers?: SchemaParser[],
83
81
  public mongoClient?: MongoClient,
84
82
  private readonly poolSize?: number,
85
- ) {
86
- }
83
+ ) {}
87
84
 
88
85
  public async connect() {
89
86
  // Connect to the database
90
- this.mongoClient = this.mongoClient ?? await new MongoClient(this.uri(), {minPoolSize: this.poolSize}).connect();
87
+ this.mongoClient =
88
+ this.mongoClient ??
89
+ (await new MongoClient(this.uri(), {
90
+ minPoolSize: this.poolSize,
91
+ }).connect());
91
92
  this.db = this.mongoClient.db(this.params.db);
92
93
  this.dbName = this.params.db;
93
94
 
@@ -146,9 +147,9 @@ export default class Nongo {
146
147
  }
147
148
 
148
149
  public async ensureIndexes(): Promise<void> {
149
-
150
+ // collections in Mongo
150
151
  const collectionNames = await this.getCollectionNames();
151
-
152
+ const indexedCollections: string[] = [];
152
153
  // Iterate over each of the model instances we have so we can ensure their indexes
153
154
  for (let i = 0; i < this.instances.length; i++) {
154
155
  const instance = this.instances[i];
@@ -159,7 +160,12 @@ export default class Nongo {
159
160
  const explicitIndexes = instance.getMongoIndexes();
160
161
  const collName = instance.collection;
161
162
  try {
162
- await this.ensureCollectionIndexes(schema, collName, explicitIndexes, collectionNames);
163
+ await this.ensureCollectionIndexes(
164
+ schema,
165
+ collName,
166
+ explicitIndexes,
167
+ collectionNames,
168
+ );
163
169
  } catch (err) {
164
170
  logger.error(`Failed to ensure indexes for ${collName}`);
165
171
  logger.error(err);
@@ -170,12 +176,34 @@ export default class Nongo {
170
176
  const atlasParams = this.params.atlas;
171
177
  const atlasEnabled = atlasParams && !atlasParams.disabled;
172
178
  if (atlasEnabled && searchIndexes.length) {
173
- await new AtlasApi(atlasParams).ensureSearchIndexes(this.dbName, instance.name, searchIndexes);
179
+ await new AtlasApi(atlasParams).ensureSearchIndexes(
180
+ this.dbName,
181
+ instance.name,
182
+ searchIndexes,
183
+ );
184
+ }
185
+ // If the instance we've just indexed has a revision,
186
+ // add to list, so we don't drop it
187
+ indexedCollections.push(collName);
188
+ const revision = instance.getCollectionRevision();
189
+ if (revision) {
190
+ indexedCollections.push(revision);
174
191
  }
192
+ }
175
193
 
194
+ const dropCollections = collectionNames.filter(
195
+ (c) => !indexedCollections.includes(c),
196
+ );
197
+ for (const coll of dropCollections) {
198
+ logger.info(`Dropping ${this.dbName}.${coll}`);
199
+ await this.dropCollection(coll);
176
200
  }
177
201
  }
178
202
 
203
+ private async dropCollection(collName) {
204
+ await this.db.dropCollection(collName);
205
+ }
206
+
179
207
  public async dropDatabase() {
180
208
  await this.db.dropDatabase();
181
209
  }
@@ -258,7 +286,7 @@ export default class Nongo {
258
286
  }
259
287
 
260
288
  private async getCollectionNames(): Promise<string[]> {
261
- const collections = await (this.db.listCollections().toArray());
289
+ const collections = await this.db.listCollections().toArray();
262
290
  return collections.map((col) => col.name);
263
291
  }
264
292
 
@@ -271,7 +299,10 @@ export default class Nongo {
271
299
  const context = this.dbName + '.' + collName;
272
300
 
273
301
  // Get the existing set of indexes, we will remove the ones we want to keep
274
- const existingIndexes = await this.existingIndexes(collName, collectionNames);
302
+ const existingIndexes = await this.existingIndexes(
303
+ collName,
304
+ collectionNames,
305
+ );
275
306
 
276
307
  // Ensure all the required indexes have been applied
277
308
  const indexSet = await this.getSchemaIndexes(schema);
@@ -1,12 +0,0 @@
1
- // This file was generated using nongo-driver's TsInterfaceGenerator.
2
- export default interface DummyModelChangedObj {
3
- 'name': string;
4
- 'pets': Array<{
5
- 'species'?: string;
6
- 'likes'?: {
7
- 'food'?: string[];
8
- 'drink'?: string[];
9
- };
10
- }>;
11
- '_id'?: any;
12
- }
@@ -1,40 +0,0 @@
1
- // This file was generated using nongo-driver's TsInterfaceGenerator.
2
- export default interface DummyModelObj {
3
- 'dontStripChildren'?: any;
4
- 'dontStripChildren2'?: any;
5
- 'exampleMap'?: {[key: string]: {
6
- 'mapValueField': string;
7
- }};
8
- 'created'?: Date;
9
- 'arrayOfObject'?: object[];
10
- 'name': string;
11
- 'age': number;
12
- 'pets': Array<{
13
- 'species'?: string;
14
- 'likes'?: {
15
- 'food'?: string[];
16
- 'drink'?: string[];
17
- };
18
- }>;
19
- 'job': {
20
- 'role': string;
21
- 'at'?: string;
22
- };
23
- 'location'?: {
24
- 'address1'?: string;
25
- };
26
- 'autoInit': {
27
- 'initArray': Array<{
28
- 'nestedObj': any;
29
- }>;
30
- 'initNestedObj'?: {
31
- 'hello'?: string;
32
- };
33
- 'initNestedNative'?: any;
34
- };
35
- 'notEmptyFields'?: {
36
- 'aString': string;
37
- 'anArray': string[];
38
- };
39
- '_id'?: any;
40
- }