mongoose 6.6.2 → 6.6.4

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/.mocharc.yml CHANGED
@@ -1,2 +1,4 @@
1
1
  reporter: spec # better to identify failing / slow tests than "dot"
2
2
  ui: bdd # explicitly setting, even though it is mocha default
3
+ require:
4
+ - test/mocha-fixtures.js
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ const schemaMerge = require('../schema/merge');
3
+ const specialProperties = require('../../helpers/specialProperties');
4
+ const isBsonType = require('../../helpers/isBsonType');
5
+ const ObjectId = require('../../types/objectid');
6
+ const isObject = require('../../helpers/isObject');
7
+ /**
8
+ * Merges `from` into `to` without overwriting existing properties.
9
+ *
10
+ * @param {Object} to
11
+ * @param {Object} from
12
+ * @param {String} [path]
13
+ * @api private
14
+ */
15
+
16
+ module.exports = function mergeDiscriminatorSchema(to, from, path) {
17
+ const keys = Object.keys(from);
18
+ let i = 0;
19
+ const len = keys.length;
20
+ let key;
21
+
22
+ path = path || '';
23
+
24
+ while (i < len) {
25
+ key = keys[i++];
26
+ if (key === 'discriminators' || key === 'base' || key === '_applyDiscriminators') {
27
+ continue;
28
+ }
29
+ if (path === 'tree' && from != null && from.instanceOfSchema) {
30
+ continue;
31
+ }
32
+ if (specialProperties.has(key)) {
33
+ continue;
34
+ }
35
+ if (to[key] == null) {
36
+ to[key] = from[key];
37
+ } else if (isObject(from[key])) {
38
+ if (!isObject(to[key])) {
39
+ to[key] = {};
40
+ }
41
+ if (from[key] != null) {
42
+ // Skip merging schemas if we're creating a discriminator schema and
43
+ // base schema has a given path as a single nested but discriminator schema
44
+ // has the path as a document array, or vice versa (gh-9534)
45
+ if ((from[key].$isSingleNested && to[key].$isMongooseDocumentArray) ||
46
+ (from[key].$isMongooseDocumentArray && to[key].$isSingleNested)) {
47
+ continue;
48
+ } else if (from[key].instanceOfSchema) {
49
+ if (to[key].instanceOfSchema) {
50
+ schemaMerge(to[key], from[key].clone(), true);
51
+ } else {
52
+ to[key] = from[key].clone();
53
+ }
54
+ continue;
55
+ } else if (isBsonType(from[key], 'ObjectID')) {
56
+ to[key] = new ObjectId(from[key]);
57
+ continue;
58
+ }
59
+ }
60
+ mergeDiscriminatorSchema(to[key], from[key], path ? path + '.' + key : key);
61
+ }
62
+ }
63
+ };
@@ -4,6 +4,7 @@ const Mixed = require('../../schema/mixed');
4
4
  const defineKey = require('../document/compile').defineKey;
5
5
  const get = require('../get');
6
6
  const utils = require('../../utils');
7
+ const mergeDiscriminatorSchema = require('../../helpers/discriminator/mergeDiscriminatorSchema');
7
8
 
8
9
  const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = {
9
10
  toJSON: true,
@@ -108,8 +109,7 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
108
109
  }
109
110
  }
110
111
 
111
- utils.merge(schema, baseSchema, {
112
- isDiscriminatorSchemaMerge: true,
112
+ mergeDiscriminatorSchema(schema, baseSchema, {
113
113
  omit: { discriminators: true, base: true, _applyDiscriminators: true },
114
114
  omitNested: conflictingPaths.reduce((cur, path) => {
115
115
  cur['tree.' + path] = true;
@@ -12,6 +12,10 @@ const isDefiningProjection = require('./isDefiningProjection');
12
12
  */
13
13
 
14
14
  module.exports = function isPathExcluded(projection, path) {
15
+ if (projection == null) {
16
+ return false;
17
+ }
18
+
15
19
  if (path === '_id') {
16
20
  return projection._id === 0;
17
21
  }
@@ -27,16 +27,16 @@ module.exports = function setupTimestamps(schema, timestamps) {
27
27
 
28
28
  schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt };
29
29
 
30
- if (updatedAt && !schema.paths[updatedAt]) {
31
- schemaAdditions[updatedAt] = Date;
32
- }
33
-
34
30
  if (createdAt && !schema.paths[createdAt]) {
35
31
  const baseImmutableCreatedAt = schema.base.get('timestamps.createdAt.immutable');
36
32
  const immutable = baseImmutableCreatedAt != null ? baseImmutableCreatedAt : true;
37
33
  schemaAdditions[createdAt] = { [schema.options.typeKey || 'type']: Date, immutable };
38
34
  }
39
35
 
36
+ if (updatedAt && !schema.paths[updatedAt]) {
37
+ schemaAdditions[updatedAt] = Date;
38
+ }
39
+
40
40
  schema.add(schemaAdditions);
41
41
 
42
42
  schema.pre('save', function timestampsPreSave(next) {
package/lib/model.js CHANGED
@@ -51,11 +51,13 @@ const {
51
51
  getRelatedDBIndexes,
52
52
  getRelatedSchemaIndexes
53
53
  } = require('./helpers/indexes/getRelatedIndexes');
54
+ const isPathExcluded = require('./helpers/projection/isPathExcluded');
54
55
  const decorateDiscriminatorIndexOptions = require('./helpers/indexes/decorateDiscriminatorIndexOptions');
55
56
  const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
56
57
  const leanPopulateMap = require('./helpers/populate/leanPopulateMap');
57
58
  const modifiedPaths = require('./helpers/update/modifiedPaths');
58
59
  const parallelLimit = require('./helpers/parallelLimit');
60
+ const parentPaths = require('./helpers/path/parentPaths');
59
61
  const prepareDiscriminatorPipeline = require('./helpers/aggregate/prepareDiscriminatorPipeline');
60
62
  const pushNestedArrayPaths = require('./helpers/model/pushNestedArrayPaths');
61
63
  const removeDeselectedForeignField = require('./helpers/populate/removeDeselectedForeignField');
@@ -760,6 +762,19 @@ Model.prototype.$__delta = function() {
760
762
  }
761
763
  }
762
764
 
765
+ // If this path is set to default, and either this path or one of
766
+ // its parents is excluded, don't treat this path as dirty.
767
+ if (this.$isDefault(data.path) && this.$__.selected) {
768
+ if (data.path.indexOf('.') === -1 && isPathExcluded(this.$__.selected, data.path)) {
769
+ continue;
770
+ }
771
+
772
+ const pathsToCheck = parentPaths(data.path);
773
+ if (pathsToCheck.find(path => isPathExcluded(this.$__.isSelected, path))) {
774
+ continue;
775
+ }
776
+ }
777
+
763
778
  if (divergent.length) continue;
764
779
  if (value === undefined) {
765
780
  operand(this, where, delta, data, 1, '$unset');
@@ -798,6 +813,11 @@ Model.prototype.$__delta = function() {
798
813
  if (this.$__.version) {
799
814
  this.$__version(where, delta);
800
815
  }
816
+
817
+ if (Object.keys(delta).length === 0) {
818
+ return [where, null];
819
+ }
820
+
801
821
  return [where, delta];
802
822
  };
803
823
 
@@ -1196,7 +1216,6 @@ Model.exists = function exists(filter, options, callback) {
1196
1216
  */
1197
1217
 
1198
1218
  Model.discriminator = function(name, schema, options) {
1199
-
1200
1219
  let model;
1201
1220
  if (typeof name === 'function') {
1202
1221
  model = name;
package/lib/query.js CHANGED
@@ -2402,6 +2402,10 @@ Query.prototype.merge = function(source) {
2402
2402
 
2403
2403
  utils.merge(this._mongooseOptions, source._mongooseOptions);
2404
2404
 
2405
+ return this;
2406
+ } else if (this.model != null && source instanceof this.model.base.Types.ObjectId) {
2407
+ utils.merge(this._conditions, { _id: source }, opts);
2408
+
2405
2409
  return this;
2406
2410
  }
2407
2411
 
@@ -2951,11 +2955,14 @@ Query.prototype.distinct = function(field, conditions, callback) {
2951
2955
  * // equivalent
2952
2956
  * query.sort('field -test');
2953
2957
  *
2958
+ * // also possible is to use a array with array key-value pairs
2959
+ * query.sort([['field', 'asc']]);
2960
+ *
2954
2961
  * #### Note:
2955
2962
  *
2956
2963
  * Cannot be used with `distinct()`
2957
2964
  *
2958
- * @param {Object|String} arg
2965
+ * @param {Object|String|Array<Array<(string | number)>>} arg
2959
2966
  * @return {Query} this
2960
2967
  * @see cursor.sort https://docs.mongodb.org/manual/reference/method/cursor.sort/
2961
2968
  * @api public
package/lib/schema.js CHANGED
@@ -502,25 +502,21 @@ Schema.prototype.defaultOptions = function(options) {
502
502
  *
503
503
  * #### Example:
504
504
  *
505
- * const options = { discriminatorKey: 'kind' };
505
+ * const eventSchema = new mongoose.Schema({ timestamp: Date }, { discriminatorKey: 'kind' });
506
+ *
507
+ * const clickedEventSchema = new mongoose.Schema({ element: String }, { discriminatorKey: 'kind' });
508
+ * const ClickedModel = eventSchema.discriminator('clicked', clickedEventSchema);
506
509
  *
507
- * const eventSchema = new mongoose.Schema({ time: Date }, options);
508
510
  * const Event = mongoose.model('Event', eventSchema);
509
511
  *
510
- * // ClickedLinkEvent is a special type of Event that has
511
- * // a URL.
512
- * const ClickedLinkEvent = Event.discriminator('ClickedLink',
513
- * new mongoose.Schema({ url: String }, options));
512
+ * Event.discriminators['clicked']; // Model { clicked }
514
513
  *
515
- * // When you create a generic event, it can't have a URL field...
516
- * const genericEvent = new Event({ time: Date.now(), url: 'google.com' });
517
- * assert.ok(!genericEvent.url);
518
- * // But a ClickedLinkEvent can
519
- * const clickedEvent = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
520
- * assert.ok(clickedEvent.url);
514
+ * const doc = await Event.create({ kind: 'clicked', element: '#hero' });
515
+ * doc.element; // '#hero'
516
+ * doc instanceof ClickedModel; // true
521
517
  *
522
518
  * @param {String} name the name of the discriminator
523
- * @param {Schema} schema the Schema of the discriminated Schema
519
+ * @param {Schema} schema the discriminated Schema
524
520
  * @return {Schema} the Schema instance
525
521
  * @api public
526
522
  */
Binary file
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "6.6.2",
4
+ "version": "6.6.4",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -28,9 +28,9 @@
28
28
  "sift": "16.0.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@babel/core": "7.19.0",
32
- "@typescript-eslint/eslint-plugin": "5.36.2",
33
- "@typescript-eslint/parser": "5.36.2",
31
+ "@babel/core": "7.19.3",
32
+ "@typescript-eslint/eslint-plugin": "5.38.1",
33
+ "@typescript-eslint/parser": "5.38.1",
34
34
  "acquit": "1.2.1",
35
35
  "acquit-ignore": "0.2.0",
36
36
  "acquit-require": "0.1.1",
@@ -43,17 +43,17 @@
43
43
  "cheerio": "1.0.0-rc.12",
44
44
  "crypto-browserify": "3.12.0",
45
45
  "dox": "1.0.0",
46
- "eslint": "8.23.0",
46
+ "eslint": "8.24.0",
47
47
  "eslint-plugin-mocha-no-only": "1.1.1",
48
48
  "express": "^4.18.1",
49
49
  "highlight.js": "11.6.0",
50
50
  "lodash.isequal": "4.5.0",
51
51
  "lodash.isequalwith": "4.4.0",
52
- "marked": "4.1.0",
52
+ "marked": "4.1.1",
53
53
  "mkdirp": "^1.0.4",
54
54
  "mocha": "10.0.0",
55
55
  "moment": "2.x",
56
- "mongodb-memory-server": "8.9.1",
56
+ "mongodb-memory-server": "8.9.3",
57
57
  "ncp": "^2.0.0",
58
58
  "nyc": "15.1.0",
59
59
  "pug": "3.0.2",
@@ -61,8 +61,8 @@
61
61
  "sinon": "14.0.0",
62
62
  "stream-browserify": "3.0.0",
63
63
  "ts-benchmark": "^1.1.10",
64
- "tsd": "0.23.0",
65
- "typescript": "4.8.3",
64
+ "tsd": "0.24.1",
65
+ "typescript": "4.8.4",
66
66
  "uuid": "9.0.0",
67
67
  "webpack": "5.74.0"
68
68
  },
package/types/index.d.ts CHANGED
@@ -162,19 +162,20 @@ declare module 'mongoose' {
162
162
  : M
163
163
  : M;
164
164
 
165
- export type DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, T> = T extends Schema<infer T1, infer T2, infer T3, infer T4, infer T5>
166
- ? Schema<Omit<DocType, keyof T1> & T1, DiscriminatorModel<T2, M>, T3 | TInstanceMethods, T4 | TQueryHelpers, T5 | TVirtuals>
167
- : Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals>;
165
+ export type DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods, DisSchema> =
166
+ DisSchema extends Schema<infer DisSchemaEDocType, infer DisSchemaM, infer DisSchemaInstanceMethods, infer DisSchemaQueryhelpers, infer DisSchemaVirtuals, infer DisSchemaStatics>
167
+ ? Schema<Omit<DocType, keyof DisSchemaEDocType> & DisSchemaEDocType, DiscriminatorModel<DisSchemaM, M>, DisSchemaInstanceMethods | TInstanceMethods, DisSchemaQueryhelpers | TQueryHelpers, DisSchemaVirtuals | TVirtuals, DisSchemaStatics & TStaticMethods>
168
+ : Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods>;
168
169
 
169
170
  type QueryResultType<T> = T extends Query<infer ResultType, any> ? ResultType : never;
170
171
 
171
172
  type PluginFunction<
172
173
  DocType,
173
- M = Model<DocType, any, any, any>,
174
- TInstanceMethods = {},
175
- TQueryHelpers = {},
176
- TVirtuals = {},
177
- TStaticMethods = {}> = (schema: Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods>, opts?: any) => void;
174
+ M,
175
+ TInstanceMethods,
176
+ TQueryHelpers,
177
+ TVirtuals,
178
+ TStaticMethods> = (schema: Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods>, opts?: any) => void;
178
179
 
179
180
  export class Schema<
180
181
  EnforcedDocType = any,
@@ -207,7 +208,7 @@ declare module 'mongoose' {
207
208
  /** Returns a copy of this schema */
208
209
  clone<T = this>(): T;
209
210
 
210
- discriminator<T = Schema>(name: string, schema: T): DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, T>;
211
+ discriminator<DisSchema = Schema>(name: string, schema: DisSchema): DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods, DisSchema>;
211
212
 
212
213
  /** Returns a new schema that has the picked `paths` from this schema. */
213
214
  pick<T = this>(paths: string[], options?: SchemaOptions): T;
@@ -263,7 +264,7 @@ declare module 'mongoose' {
263
264
  pathType(path: string): string;
264
265
 
265
266
  /** Registers a plugin for this schema. */
266
- plugin<PFunc extends PluginFunction<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods>, POptions extends Parameters<PFunc>[1] = Parameters<PFunc>[1]>(fn: PFunc, opts?: POptions): this;
267
+ plugin<PFunc extends PluginFunction<DocType, M, any, any, any, any>, POptions extends Parameters<PFunc>[1] = Parameters<PFunc>[1]>(fn: PFunc, opts?: POptions): this;
267
268
 
268
269
  /** Defines a post hook for the model. */
269
270
  post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, T>): this;
package/types/models.d.ts CHANGED
@@ -146,9 +146,9 @@ declare module 'mongoose' {
146
146
  * if you use `create()`) because with `bulkWrite()` there is only one network
147
147
  * round trip to the MongoDB server.
148
148
  */
149
- bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation<T extends {} ? T : any>>, options: mongodb.BulkWriteOptions & MongooseBulkWriteOptions, callback: Callback<mongodb.BulkWriteResult>): void;
150
- bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation<T extends {} ? T : any>>, callback: Callback<mongodb.BulkWriteResult>): void;
151
- bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation<T extends {} ? T : any>>, options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions): Promise<mongodb.BulkWriteResult>;
149
+ bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation<T extends Document ? any : (T extends {} ? T : any)>>, options: mongodb.BulkWriteOptions & MongooseBulkWriteOptions, callback: Callback<mongodb.BulkWriteResult>): void;
150
+ bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation<T extends Document ? any : (T extends {} ? T : any)>>, callback: Callback<mongodb.BulkWriteResult>): void;
151
+ bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation<T extends Document ? any : (T extends {} ? T : any)>>, options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions): Promise<mongodb.BulkWriteResult>;
152
152
 
153
153
  /**
154
154
  * Sends multiple `save()` calls in a single `bulkWrite()`. This is faster than
package/types/query.d.ts CHANGED
@@ -601,7 +601,7 @@ declare module 'mongoose' {
601
601
  snapshot(val?: boolean): this;
602
602
 
603
603
  /** Sets the sort order. If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. */
604
- sort(arg?: string | { [key: string]: SortOrder | { $meta: 'textScore' } } | undefined | null): this;
604
+ sort(arg?: string | { [key: string]: SortOrder | { $meta: 'textScore' } } | [string, SortOrder][] | undefined | null): this;
605
605
 
606
606
  /** Sets the tailable option (for use with capped collections). */
607
607
  tailable(bool?: boolean, opts?: {
@@ -616,7 +616,7 @@ declare module 'mongoose' {
616
616
  then: Promise<ResultType>['then'];
617
617
 
618
618
  /** Converts this query to a customized, reusable query constructor with all arguments and options retained. */
619
- toConstructor(): typeof this;
619
+ toConstructor(): typeof Query<ResultType, DocType, THelpers, RawDocType>;
620
620
 
621
621
  /** Declare and/or execute this query as an update() operation. */
622
622
  update(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
@@ -201,7 +201,7 @@ declare module 'mongoose' {
201
201
  /**
202
202
  * Query helper functions.
203
203
  */
204
- query?: Record<any, <T extends QueryWithHelpers<unknown, DocType>>(this: T, ...args: any) => T> | QueryHelpers,
204
+ query?: Record<any, <T extends QueryWithHelpers<unknown, HydratedDocument<DocType>>>(this: T, ...args: any) => T> | QueryHelpers,
205
205
 
206
206
  /**
207
207
  * Set whether to cast non-array values to arrays.
@@ -100,7 +100,7 @@ declare module 'mongoose' {
100
100
  * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
101
101
  * build an index on this path when the model is compiled.
102
102
  */
103
- index?: boolean | number | IndexOptions | '2d' | '2dsphere' | 'hashed' | 'text';
103
+ index?: boolean | IndexDirection;
104
104
 
105
105
  /**
106
106
  * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose