@mikro-orm/mongodb 7.3.0-dev.20 → 7.3.0-dev.22

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/MongoDriver.d.ts CHANGED
@@ -37,6 +37,8 @@ export declare class MongoDriver extends DatabaseDriver<MongoConnection> {
37
37
  renameFields<T extends object>(entityName: EntityName<T>, data: T, dotPaths?: boolean, object?: boolean, root?: boolean): T;
38
38
  /** Relations are stored as references, so conditions can only compare them by PK, e.g. `{ author: { id } }` becomes `{ author: _id }`. */
39
39
  private inlineRelationPrimaryKey;
40
+ private convertRegExpOperator;
41
+ private convertRegExpOperators;
40
42
  private convertObjectIds;
41
43
  private buildFilterById;
42
44
  protected buildFields<T extends object, P extends string = never>(entityName: EntityName<T>, populate: PopulateOptions<T>[], fields?: readonly EntityField<T, P>[], exclude?: string[]): string[] | undefined;
package/MongoDriver.js CHANGED
@@ -95,13 +95,19 @@ export class MongoDriver extends DatabaseDriver {
95
95
  }
96
96
  async findWithPartitionLimit(entityName, where, orderBy, fields, partitionLimit, options) {
97
97
  const meta = this.metadata.find(entityName);
98
- const { limit, offset = 0 } = partitionLimit;
98
+ const { limit, offset = 0, owners } = partitionLimit;
99
99
  // Resolve the partition property to its DB field name; callers always pass
100
100
  // a declared property on the target meta (FK of the owning side).
101
101
  const prop = meta.properties[partitionLimit.partitionBy];
102
102
  const partitionField = prop.fieldNames[0];
103
103
  const pipeline = [];
104
104
  pipeline.push({ $match: where });
105
+ // an M:N owner array holds several partitions, so rank each row once per requested owner, like a pivot row in SQL
106
+ if (owners) {
107
+ pipeline.push({ $addFields: { __partition: `$${partitionField}` } });
108
+ pipeline.push({ $unwind: '$__partition' });
109
+ pipeline.push({ $match: { __partition: { $in: owners } } });
110
+ }
105
111
  if (orderBy.length > 0) {
106
112
  const sortSpec = {};
107
113
  for (const order of orderBy) {
@@ -115,7 +121,7 @@ export class MongoDriver extends DatabaseDriver {
115
121
  // $sort before $group ensures $push collects in correct order
116
122
  pipeline.push({
117
123
  $group: {
118
- _id: `$${partitionField}`,
124
+ _id: owners ? '$__partition' : `$${partitionField}`,
119
125
  __docs: { $push: '$$ROOT' },
120
126
  },
121
127
  });
@@ -131,9 +137,19 @@ export class MongoDriver extends DatabaseDriver {
131
137
  for (const field of fields) {
132
138
  projection[field] = 1;
133
139
  }
140
+ if (owners) {
141
+ projection.__partition = 1;
142
+ }
134
143
  pipeline.push({ $project: projection });
135
144
  }
136
145
  const res = await this.rethrow(this.getConnection('read').aggregate(entityName, pipeline, options.ctx, options.logging, options.signal));
146
+ if (owners) {
147
+ partitionLimit.partitions = res.map((row) => {
148
+ const owner = row.__partition;
149
+ delete row.__partition;
150
+ return [owner, row._id];
151
+ });
152
+ }
137
153
  return res.map(r => this.mapResult(r, meta));
138
154
  }
139
155
  async findOne(entityName, where, options = { populate: [], orderBy: {} }) {
@@ -200,7 +216,7 @@ export class MongoDriver extends DatabaseDriver {
200
216
  const meta = this.metadata.find(entityName);
201
217
  const pk = meta.getPrimaryProps()[0].fieldNames[0] ?? '_id';
202
218
  const normalizedWhere = Utils.isPrimaryKey(where) ? { [pk]: where } : where;
203
- const renameWhere = this.renameFields(entityName, normalizedWhere);
219
+ const renameWhere = this.renameFields(entityName, normalizedWhere, true);
204
220
  const source = await this.rethrow(this.getConnection('read').find(entityName, renameWhere, { ctx: options.ctx, limit: 1 }));
205
221
  if (!source.length) {
206
222
  throw new Error('Cannot clone: no entity found matching the given condition');
@@ -239,6 +255,8 @@ export class MongoDriver extends DatabaseDriver {
239
255
  res.row = { _id: res.insertId };
240
256
  return res;
241
257
  }
258
+ // work on a copy, `em.upsert()` builds the entity from the caller's data and must not see the `$inc`
259
+ data = { ...data };
242
260
  this.handleVersionProperty(entityName, data, true);
243
261
  data = this.renameFields(entityName, data);
244
262
  where = this.renameFields(entityName, where, true);
@@ -265,6 +283,7 @@ export class MongoDriver extends DatabaseDriver {
265
283
  return row;
266
284
  });
267
285
  data = data.map(row => {
286
+ row = { ...row };
268
287
  this.handleVersionProperty(entityName, row, true);
269
288
  return this.renameFields(entityName, row);
270
289
  });
@@ -392,6 +411,7 @@ export class MongoDriver extends DatabaseDriver {
392
411
  }
393
412
  return;
394
413
  }
414
+ let key = k;
395
415
  // per-target polymorphic keys like `likeable[Comment]` resolve to the relation, whose conditions need joins
396
416
  const [propName, targetName] = QueryHelper.splitPolymorphicKey(k);
397
417
  const prop = meta?.properties[propName];
@@ -461,10 +481,12 @@ export class MongoDriver extends DatabaseDriver {
461
481
  }
462
482
  if (prop.fieldNames) {
463
483
  Utils.renameKey(copiedData, k, prop.fieldNames[0]);
484
+ key = prop.fieldNames[0];
464
485
  }
465
486
  }
466
- if (Utils.isPlainObject(copiedData[k]) && '$re' in copiedData[k]) {
467
- copiedData[k] = new RegExp(copiedData[k].$re);
487
+ // `dotPaths` marks a query, entity data (e.g. JSON values) must stay as-is
488
+ if (dotPaths) {
489
+ copiedData[key] = this.convertRegExpOperator(copiedData[key]);
468
490
  }
469
491
  });
470
492
  return copiedData;
@@ -486,6 +508,29 @@ export class MongoDriver extends DatabaseDriver {
486
508
  }
487
509
  throw new Error(`Unsupported condition on relation ${meta.className}.${prop.name}, MongoDB can query relations only by primary key or entity reference.`);
488
510
  }
511
+ convertRegExpOperator(value) {
512
+ if (!Utils.isPlainObject(value)) {
513
+ return value;
514
+ }
515
+ let cond = '$not' in value ? { ...value, $not: this.convertRegExpOperator(value.$not) } : value;
516
+ if (Utils.isPlainObject(cond.$elemMatch)) {
517
+ cond = { ...cond, $elemMatch: this.convertRegExpOperators(cond.$elemMatch) };
518
+ }
519
+ if (!('$re' in cond)) {
520
+ return cond;
521
+ }
522
+ const { $re, ...rest } = cond;
523
+ // mongo has no `$re`: a RegExp when it stands alone, `$regex` next to other operators
524
+ return Utils.hasObjectKeys(rest) ? { ...rest, $regex: $re } : new RegExp($re);
525
+ }
526
+ convertRegExpOperators(where) {
527
+ return Object.fromEntries(Object.entries(where).map(([k, v]) => [
528
+ k,
529
+ k in GroupOperator && Array.isArray(v)
530
+ ? v.map(c => this.convertRegExpOperators(c))
531
+ : this.convertRegExpOperator(v),
532
+ ]));
533
+ }
489
534
  convertObjectIds(data) {
490
535
  if (data instanceof ObjectId) {
491
536
  return data;
@@ -17,7 +17,7 @@ export declare class MongoEntityManager<Driver extends MongoDriver = MongoDriver
17
17
  /**
18
18
  * @inheritDoc
19
19
  */
20
- stream<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<StreamOptions<NoInfer<Entity>, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
20
+ stream<Entity extends object, Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(entityName: EntityName<Entity>, options?: WithUsingOptions<StreamOptions<Entity, Hint, Fields, Excludes>, NoInfer<Entity>, Using>): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>>;
21
21
  getCollection<T extends Document>(entityOrCollectionName: EntityName<T> | string): Collection<T>;
22
22
  /**
23
23
  * @inheritDoc
@@ -138,7 +138,7 @@ export class MongoSchemaGenerator extends AbstractSchemaGenerator {
138
138
  // The array-form escape hatch passes raw [spec, options] to the driver; fold `where`
139
139
  // into the options dict (on a clone, to avoid mutating the user's metadata).
140
140
  const opts = { ...index.options[1] };
141
- this.applyPartialFilter(opts, index.where, index.name, meta.className);
141
+ this.applyPartialFilter(opts, index.where, index.name, meta);
142
142
  res.push([collection.collectionName, collection.createIndex(index.options[0], opts)]);
143
143
  return;
144
144
  }
@@ -176,7 +176,7 @@ export class MongoSchemaGenerator extends AbstractSchemaGenerator {
176
176
  if (index.invisible) {
177
177
  indexOptions.hidden = true;
178
178
  }
179
- this.applyPartialFilter(indexOptions, index.where, index.name, meta.className);
179
+ this.applyPartialFilter(indexOptions, index.where, index.name, meta);
180
180
  res.push([collection.collectionName, this.executeQuery(collection, 'createIndex', fieldOrSpec, indexOptions)]);
181
181
  });
182
182
  return res;
@@ -185,20 +185,21 @@ export class MongoSchemaGenerator extends AbstractSchemaGenerator {
185
185
  * An explicit `options.partialFilterExpression` wins over `where` — this preserves the
186
186
  * long-standing `options: { partialFilterExpression }` escape hatch.
187
187
  */
188
- applyPartialFilter(options, where, indexName, entityName) {
188
+ applyPartialFilter(options, where, indexName, meta) {
189
189
  if (where == null) {
190
190
  return;
191
191
  }
192
192
  if (options.partialFilterExpression != null) {
193
193
  this.config
194
194
  .getLogger()
195
- .warn('schema', `Index '${indexName ?? '(unnamed)'}' on entity '${entityName}': both \`where\` and \`options.partialFilterExpression\` are set; \`options.partialFilterExpression\` wins.`);
195
+ .warn('schema', `Index '${indexName ?? '(unnamed)'}' on entity '${meta.className}': both \`where\` and \`options.partialFilterExpression\` are set; \`options.partialFilterExpression\` wins.`);
196
196
  return;
197
197
  }
198
198
  if (typeof where === 'string') {
199
- throw new Error(`Index '${indexName ?? '(unnamed)'}' on entity '${entityName}': string \`where\` is not supported on MongoDB; pass an object/FilterQuery (it maps to MongoDB's \`partialFilterExpression\`).`);
199
+ throw new Error(`Index '${indexName ?? '(unnamed)'}' on entity '${meta.className}': string \`where\` is not supported on MongoDB; pass an object/FilterQuery (it maps to MongoDB's \`partialFilterExpression\`).`);
200
200
  }
201
- options.partialFilterExpression = where;
201
+ // map property names to field names, the same way the driver does for queries
202
+ options.partialFilterExpression = this.driver.renameFields(meta.class, where, true);
202
203
  }
203
204
  async executeQuery(collection, method, ...args) {
204
205
  const now = Date.now();
@@ -227,7 +228,7 @@ export class MongoSchemaGenerator extends AbstractSchemaGenerator {
227
228
  unique: true,
228
229
  ...index.options,
229
230
  };
230
- this.applyPartialFilter(indexOptions, index.where, index.name, meta.className);
231
+ this.applyPartialFilter(indexOptions, index.where, index.name, meta);
231
232
  res.push([collection.collectionName, this.executeQuery(collection, 'createIndex', fieldOrSpec, indexOptions)]);
232
233
  });
233
234
  return res;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/mongodb",
3
- "version": "7.3.0-dev.20",
3
+ "version": "7.3.0-dev.22",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
5
  "keywords": [
6
6
  "data-mapper",
@@ -50,10 +50,10 @@
50
50
  "mongodb": "7.8.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@mikro-orm/core": "^7.2.7"
53
+ "@mikro-orm/core": "^7.2.9"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.3.0-dev.20"
56
+ "@mikro-orm/core": "7.3.0-dev.22"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">= 22.17.0"