From d3e22af841abb65ce5366c5fc0fa605d5e8ccb53 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Fri, 12 Jan 2024 17:01:39 -0500 Subject: [PATCH 01/13] fix(document): handle embedded recursive discriminators on nested path defined using Schema.prototype.discriminator Fix #14245 --- .../applyEmbeddedDiscriminators.js | 9 ++-- test/document.test.js | 48 +++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/lib/helpers/discriminator/applyEmbeddedDiscriminators.js b/lib/helpers/discriminator/applyEmbeddedDiscriminators.js index 840a4dc628e..9a04ecb072f 100644 --- a/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +++ b/lib/helpers/discriminator/applyEmbeddedDiscriminators.js @@ -19,11 +19,10 @@ function applyEmbeddedDiscriminators(schema, seen = new WeakSet()) { if (schemaType._appliedDiscriminators) { continue; } - for (const disc of schemaType.schema._applyDiscriminators.keys()) { - schemaType.discriminator( - disc, - schemaType.schema._applyDiscriminators.get(disc) - ); + for (const discriminatorKey of schemaType.schema._applyDiscriminators.keys()) { + const discriminatorSchema = schemaType.schema._applyDiscriminators.get(discriminatorKey); + applyEmbeddedDiscriminators(discriminatorSchema, seen); + schemaType.discriminator(discriminatorKey, discriminatorSchema); } schemaType._appliedDiscriminators = true; } diff --git a/test/document.test.js b/test/document.test.js index 7c416967f1b..484294ce0d1 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -12787,6 +12787,54 @@ describe('document', function() { await doc2.save(); }); + it('handles embedded recursive discriminators on nested path defined using Schema.prototype.discriminator (gh-14245)', async function() { + const baseSchema = new Schema({ + type: { type: Number, required: true } + }, { discriminatorKey: 'type' }); + + class Base { + whoAmI() { return 'I am Base'; } + } + + baseSchema.loadClass(Base); + + class NumberTyped extends Base { + whoAmI() { return 'I am NumberTyped'; } + } + + class StringTyped extends Base { + whoAmI() { return 'I am StringTyped'; } + } + + const selfRefSchema = new Schema({ + self: { type: [baseSchema], required: true } + }); + + class SelfReferenceTyped extends Base { + whoAmI() { return 'I am SelfReferenceTyped'; } + } + + selfRefSchema.loadClass(SelfReferenceTyped); + baseSchema.discriminator(5, selfRefSchema); + + const numberTypedSchema = new Schema({}).loadClass(NumberTyped); + const stringTypedSchema = new Schema({}).loadClass(StringTyped); + baseSchema.discriminator(1, numberTypedSchema); + baseSchema.discriminator(3, stringTypedSchema); + const containerSchema = new Schema({ items: [baseSchema] }); + const containerModel = db.model('Test', containerSchema); + + const instance = await containerModel.create({ + items: [{ type: 5, self: [{ type: 1 }, { type: 3 }] }] + }); + + assert.equal(instance.items[0].whoAmI(), 'I am SelfReferenceTyped'); + assert.deepStrictEqual(instance.items[0].self.map(item => item.whoAmI()), [ + 'I am NumberTyped', + 'I am StringTyped' + ]); + }); + it('can use `collection` as schema name (gh-13956)', async function() { const schema = new mongoose.Schema({ name: String, collection: String }); const Test = db.model('Test', schema); From 64fa4705c807e1ed285f0c5355e37854a5485f1b Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 17 Jan 2024 06:59:00 -0500 Subject: [PATCH 02/13] docs(model+query+findoneandupdate): add more details about `overwriteDiscriminatorKey` option to docs Fix #14246 --- docs/tutorials/findoneandupdate.md | 38 +++++++++++++++++++++++++++++- lib/model.js | 4 ++++ lib/query.js | 5 +++- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/docs/tutorials/findoneandupdate.md b/docs/tutorials/findoneandupdate.md index c589b15b952..5ca0314fff6 100644 --- a/docs/tutorials/findoneandupdate.md +++ b/docs/tutorials/findoneandupdate.md @@ -7,10 +7,18 @@ However, there are some cases where you need to use [`findOneAndUpdate()`](https * [Atomic Updates](#atomic-updates) * [Upsert](#upsert) * [The `rawResult` Option](#raw-result) +* [Updating Discriminator Keys](#updating-discriminator-keys) ## Getting Started -As the name implies, `findOneAndUpdate()` finds the first document that matches a given `filter`, applies an `update`, and returns the document. By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. +As the name implies, `findOneAndUpdate()` finds the first document that matches a given `filter`, applies an `update`, and returns the document. +The `findOneAndUpdate()` function has the following signature: + +```javascript +function findOneAndUpdate(filter, update, options) {} +``` + +By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. ```acquit [require:Tutorial.*findOneAndUpdate.*basic case] @@ -78,3 +86,31 @@ Here's what the `res` object from the above example looks like: age: 29 }, ok: 1 } ``` + +## Updating Discriminator Keys + +Mongoose prevents updating the [discriminator key](https://mongoosejs.com/docs/discriminators.html#discriminator-keys) using `findOneAndUpdate()` by default. +For example, suppose you have the following discriminator models. + +```javascript +const eventSchema = new mongoose.Schema({ time: Date }); +const Event = db.model('Event', eventSchema); + +const ClickedLinkEvent = Event.discriminator( + 'ClickedLink', + new mongoose.Schema({ url: String }) +); + +const SignedUpEvent = Event.discriminator( + 'SignedUp', + new mongoose.Schema({ username: String }) +); +``` + +Mongoose will remove `__t` (the default discriminator key) from the `update` parameter, if `__t` is set. +This is to prevent unintentional updates to the discriminator key; for example, if you're passing untrusted user input to the `update` parameter. +However, you can tell Mongoose to allow updating the discriminator key by setting the `overwriteDiscriminatorKey` option to `true` as shown below. + +```acquit +[require:use overwriteDiscriminatorKey to change discriminator key] +``` diff --git a/lib/model.js b/lib/model.js index e97407429aa..aee450da45d 100644 --- a/lib/model.js +++ b/lib/model.js @@ -2428,6 +2428,7 @@ Model.$where = function $where() { * @param {Boolean} [options.setDefaultsOnInsert=true] If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](https://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/4.9/interfaces/ModifyResult.html) * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. + * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key * @return {Query} * @see Tutorial https://mongoosejs.com/docs/tutorials/findoneandupdate.html * @see mongodb https://www.mongodb.com/docs/manual/reference/command/findAndModify/ @@ -2524,6 +2525,7 @@ Model.findOneAndUpdate = function(conditions, update, options) { * @param {Boolean} [options.new=false] if true, return the modified document rather than the original * @param {Object|String} [options.select] sets the document fields to return. * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. + * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key * @return {Query} * @see Model.findOneAndUpdate https://mongoosejs.com/docs/api/model.html#Model.findOneAndUpdate() * @see mongodb https://www.mongodb.com/docs/manual/reference/command/findAndModify/ @@ -3888,6 +3890,7 @@ Model.hydrate = function(obj, projection, options) { * @param {Object} [options.writeConcern=null] sets the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](https://mongoosejs.com/docs/guide.html#writeConcern) * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. + * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key * @return {Query} * @see Query docs https://mongoosejs.com/docs/queries.html * @see MongoDB docs https://www.mongodb.com/docs/manual/reference/command/update/#update-command-output @@ -3927,6 +3930,7 @@ Model.updateMany = function updateMany(conditions, doc, options) { * @param {Object} [options.writeConcern=null] sets the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](https://mongoosejs.com/docs/guide.html#writeConcern) * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. + * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key * @return {Query} * @see Query docs https://mongoosejs.com/docs/queries.html * @see MongoDB docs https://www.mongodb.com/docs/manual/reference/command/update/#update-command-output diff --git a/lib/query.js b/lib/query.js index a6063cc5fc4..5db5c0e7ef7 100644 --- a/lib/query.js +++ b/lib/query.js @@ -3213,6 +3213,7 @@ function prepareDiscriminatorCriteria(query) { * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. + * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key * @see Tutorial https://mongoosejs.com/docs/tutorials/findoneandupdate.html * @see findAndModify command https://www.mongodb.com/docs/manual/reference/command/findAndModify/ * @see ModifyResult https://mongodb.github.io/node-mongodb-native/4.9/interfaces/ModifyResult.html @@ -4003,6 +4004,7 @@ Query.prototype._replaceOne = async function _replaceOne() { * @param {Object} [options.writeConcern=null] sets the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](https://mongoosejs.com/docs/guide.html#writeConcern) * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. + * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key * @param {Function} [callback] params are (error, writeOpResult) * @return {Query} this * @see Model.update https://mongoosejs.com/docs/api/model.html#Model.update() @@ -4071,7 +4073,8 @@ Query.prototype.updateMany = function(conditions, doc, options, callback) { * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document * @param {Object} [options.writeConcern=null] sets the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](https://mongoosejs.com/docs/guide.html#writeConcern) * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. + * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. + * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key * @param {Function} [callback] params are (error, writeOpResult) * @return {Query} this * @see Model.update https://mongoosejs.com/docs/api/model.html#Model.update() From ee0d28f640d99b1fb19ec1ca54a6e016f9880d2f Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 17 Jan 2024 13:38:34 -0500 Subject: [PATCH 03/13] Update docs/tutorials/findoneandupdate.md Co-authored-by: hasezoey --- docs/tutorials/findoneandupdate.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorials/findoneandupdate.md b/docs/tutorials/findoneandupdate.md index 5ca0314fff6..3f34bf3cc6d 100644 --- a/docs/tutorials/findoneandupdate.md +++ b/docs/tutorials/findoneandupdate.md @@ -89,7 +89,7 @@ Here's what the `res` object from the above example looks like: ## Updating Discriminator Keys -Mongoose prevents updating the [discriminator key](https://mongoosejs.com/docs/discriminators.html#discriminator-keys) using `findOneAndUpdate()` by default. +Mongoose prevents updating the [discriminator key](../discriminators.html#discriminator-keys) using `findOneAndUpdate()` by default. For example, suppose you have the following discriminator models. ```javascript From cc80894fccb43cc16d5d3606888437073c479d0b Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 17 Jan 2024 13:38:42 -0500 Subject: [PATCH 04/13] Update lib/model.js Co-authored-by: hasezoey --- lib/model.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/model.js b/lib/model.js index aee450da45d..967fed3494d 100644 --- a/lib/model.js +++ b/lib/model.js @@ -3890,7 +3890,7 @@ Model.hydrate = function(obj, projection, options) { * @param {Object} [options.writeConcern=null] sets the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](https://mongoosejs.com/docs/guide.html#writeConcern) * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object. - * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key + * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key * @return {Query} * @see Query docs https://mongoosejs.com/docs/queries.html * @see MongoDB docs https://www.mongodb.com/docs/manual/reference/command/update/#update-command-output From 775aadf16be64ffc19f86aa05797095ad3d9eca3 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 26 Dec 2023 15:53:14 -0500 Subject: [PATCH 05/13] types(model): correct return type for findByIdAndDelete() Fix #14190 --- test/types/queries.test.ts | 8 ++++++++ types/models.d.ts | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/test/types/queries.test.ts b/test/types/queries.test.ts index efca12618a5..2b8ecff5504 100644 --- a/test/types/queries.test.ts +++ b/test/types/queries.test.ts @@ -518,3 +518,11 @@ function gh13630() { const x: UpdateQueryKnownOnly = { $set: { name: 'John' } }; expectAssignable>(x); } + +function gh14190() { + const userSchema = new Schema({ name: String, age: Number }); + const UserModel = model('User', userSchema); + + const doc = await UserModel.findByIdAndDelete('0'.repeat(24)); + expectType | null>(doc); +} diff --git a/types/models.d.ts b/types/models.d.ts index 2c7f54b17f8..7cb082bc372 100644 --- a/types/models.d.ts +++ b/types/models.d.ts @@ -550,8 +550,8 @@ declare module 'mongoose' { 'findOneAndDelete' >; findByIdAndDelete( - id?: mongodb.ObjectId | any, - options?: QueryOptions & { includeResultMetadata: true } + id: mongodb.ObjectId | any, + options: QueryOptions & { includeResultMetadata: true } ): QueryWithHelpers, ResultDoc, TQueryHelpers, TRawDocType, 'findOneAndDelete'>; findByIdAndDelete( id?: mongodb.ObjectId | any, From 7f9406ff44c5d8536599060c3ae38009f866ab60 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 26 Dec 2023 16:14:07 -0500 Subject: [PATCH 06/13] types(query): improve findByIdAndDelete return type for query re: #14190 --- test/types/queries.test.ts | 18 +++++++++++++++++- types/query.d.ts | 4 ++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/test/types/queries.test.ts b/test/types/queries.test.ts index 2b8ecff5504..bf20145e1b7 100644 --- a/test/types/queries.test.ts +++ b/test/types/queries.test.ts @@ -17,7 +17,7 @@ import { ProjectionFields, QueryOptions } from 'mongoose'; -import { ObjectId } from 'mongodb'; +import { ModifyResult, ObjectId } from 'mongodb'; import { expectAssignable, expectError, expectNotAssignable, expectType } from 'tsd'; import { autoTypedModel } from './models.test'; import { AutoTypedSchemaType } from './schema.test'; @@ -525,4 +525,20 @@ function gh14190() { const doc = await UserModel.findByIdAndDelete('0'.repeat(24)); expectType | null>(doc); + + const res = await UserModel.findByIdAndDelete( + '0'.repeat(24), + { includeResultMetadata: true } + ); + expectAssignable< + ModifyResult> + >(res); + + const res2 = await UserModel.find().findByIdAndDelete( + '0'.repeat(24), + { includeResultMetadata: true } + ); + expectAssignable< + ModifyResult> + >(res2); } diff --git a/types/query.d.ts b/types/query.d.ts index 2234e66f656..39ff69de9df 100644 --- a/types/query.d.ts +++ b/types/query.d.ts @@ -435,6 +435,10 @@ declare module 'mongoose' { ): QueryWithHelpers; /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */ + findByIdAndDelete( + id: mongodb.ObjectId | any, + options: QueryOptions & { includeResultMetadata: true } + ): QueryWithHelpers, DocType, THelpers, RawDocType, 'findOneAndDelete'>; findByIdAndDelete( id?: mongodb.ObjectId | any, options?: QueryOptions | null From a6e4d18ab7bbb015d9f87fd3990b8e5bf4922825 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Sun, 21 Jan 2024 14:10:00 -0500 Subject: [PATCH 07/13] style: fix lint --- test/types/queries.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/types/queries.test.ts b/test/types/queries.test.ts index bf20145e1b7..ed56bb9d7a0 100644 --- a/test/types/queries.test.ts +++ b/test/types/queries.test.ts @@ -532,7 +532,7 @@ function gh14190() { ); expectAssignable< ModifyResult> - >(res); + >(res); const res2 = await UserModel.find().findByIdAndDelete( '0'.repeat(24), @@ -540,5 +540,5 @@ function gh14190() { ); expectAssignable< ModifyResult> - >(res2); + >(res2); } From 6950c96b97a7da102444b73b86418d98e527e4e6 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 20 Feb 2024 13:16:24 -0500 Subject: [PATCH 08/13] docs(connections): add note about using `asPromise()` with `createConnection()` for error handling Fix #14266 --- docs/connections.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/connections.md b/docs/connections.md index c6a1fdf8cc3..5b65b096293 100644 --- a/docs/connections.md +++ b/docs/connections.md @@ -402,16 +402,24 @@ The `mongoose.createConnection()` function takes the same arguments as const conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options); ``` -This [connection](api/connection.html#connection_Connection) object is then used to -create and retrieve [models](api/model.html#model_Model). Models are -**always** scoped to a single connection. +This [connection](api/connection.html#connection_Connection) object is then used to create and retrieve [models](api/model.html#model_Model). +Models are **always** scoped to a single connection. ```javascript const UserModel = conn.model('User', userSchema); ``` -If you use multiple connections, you should make sure you export schemas, -**not** models. Exporting a model from a file is called the *export model pattern*. +The `createConnection()` function returns a connection instance, not a promise. +If you want to use `await` to make sure Mongoose successfully connects to MongoDB, use the [`asPromise()` function](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.asPromise()): + +```javascript +// `asPromise()` returns a promise that resolves to the connection +// once the connection succeeds, or rejects if connection failed. +const conn = await mongoose.createConnection(connectionString).asPromise(); +``` + +If you use multiple connections, you should make sure you export schemas, **not** models. +Exporting a model from a file is called the *export model pattern*. The export model pattern is limited because you can only use one connection. ```javascript From 81e36d10a3f440081f69d0ccc91b3d2f3d1da995 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 22 Feb 2024 14:55:23 -0500 Subject: [PATCH 09/13] Update docs/connections.md Co-authored-by: hasezoey --- docs/connections.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/connections.md b/docs/connections.md index 5b65b096293..2c58cfd2142 100644 --- a/docs/connections.md +++ b/docs/connections.md @@ -410,7 +410,7 @@ const UserModel = conn.model('User', userSchema); ``` The `createConnection()` function returns a connection instance, not a promise. -If you want to use `await` to make sure Mongoose successfully connects to MongoDB, use the [`asPromise()` function](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.asPromise()): +If you want to use `await` to make sure Mongoose successfully connects to MongoDB, use the [`asPromise()` function](api/connection.html#Connection.prototype.asPromise()): ```javascript // `asPromise()` returns a promise that resolves to the connection From 71d4abf45145adab53ddb1150a866fc0a2a31ca0 Mon Sep 17 00:00:00 2001 From: Sean Derrow Date: Mon, 26 Feb 2024 01:15:27 -0500 Subject: [PATCH 10/13] [fix] MongooseQueryOptions typing --- types/models.d.ts | 10 +++++----- types/query.d.ts | 37 +++++++++++++++++++++---------------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/types/models.d.ts b/types/models.d.ts index a77aa25525e..2a1b73aa05a 100644 --- a/types/models.d.ts +++ b/types/models.d.ts @@ -228,7 +228,7 @@ declare module 'mongoose' { /** Creates a `countDocuments` query: counts the number of documents that match `filter`. */ countDocuments( filter?: FilterQuery, - options?: (mongodb.CountOptions & Omit, 'lean' | 'timestamps'>) | null + options?: (mongodb.CountOptions & MongooseBaseQueryOptions) | null ): QueryWithHelpers< number, THydratedDocumentType, @@ -266,7 +266,7 @@ declare module 'mongoose' { */ deleteMany( filter?: FilterQuery, - options?: (mongodb.DeleteOptions & Omit, 'lean' | 'timestamps'>) | null + options?: (mongodb.DeleteOptions & MongooseBaseQueryOptions) | null ): QueryWithHelpers< mongodb.DeleteResult, THydratedDocumentType, @@ -291,7 +291,7 @@ declare module 'mongoose' { */ deleteOne( filter?: FilterQuery, - options?: (mongodb.DeleteOptions & Omit, 'lean' | 'timestamps'>) | null + options?: (mongodb.DeleteOptions & MongooseBaseQueryOptions) | null ): QueryWithHelpers< mongodb.DeleteResult, THydratedDocumentType, @@ -743,14 +743,14 @@ declare module 'mongoose' { updateMany( filter?: FilterQuery, update?: UpdateQuery | UpdateWithAggregationPipeline, - options?: (mongodb.UpdateOptions & Omit, 'lean'>) | null + options?: (mongodb.UpdateOptions & MongooseUpdateQueryOptions) | null ): QueryWithHelpers; /** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */ updateOne( filter?: FilterQuery, update?: UpdateQuery | UpdateWithAggregationPipeline, - options?: (mongodb.UpdateOptions & Omit, 'lean'>) | null + options?: (mongodb.UpdateOptions & MongooseUpdateQueryOptions) | null ): QueryWithHelpers; /** Creates a Query, applies the passed conditions, and returns the Query. */ diff --git a/types/query.d.ts b/types/query.d.ts index 0bdda904350..1bfb4950647 100644 --- a/types/query.d.ts +++ b/types/query.d.ts @@ -17,25 +17,30 @@ declare module 'mongoose' { */ type FilterQuery = _FilterQuery; - type MongooseQueryOptions = Pick< - QueryOptions, - 'context' | - 'lean' | - 'multipleCastError' | - 'overwriteDiscriminatorKey' | - 'populate' | - 'runValidators' | - 'sanitizeProjection' | - 'sanitizeFilter' | - 'setDefaultsOnInsert' | - 'strict' | - 'strictQuery' | - 'timestamps' | - 'translateAliases' - > & { + type MongooseBaseQueryOptionKeys = + | "context" + | "multipleCastError" + | "overwriteDiscriminatorKey" + | "populate" + | "runValidators" + | "sanitizeProjection" + | "sanitizeFilter" + | "setDefaultsOnInsert" + | "strict" + | "strictQuery" + | "translateAliases"; + + type MongooseQueryOptions< + DocType = unknown, + Keys extends keyof QueryOptions = MongooseBaseQueryOptionKeys | "timestamps" | "lean" + > = Pick, Keys> & { [other: string]: any; }; + type MongooseBaseQueryOptions = MongooseQueryOptions; + + type MongooseUpdateQueryOptions = MongooseQueryOptions; + type ProjectionFields = { [Key in keyof DocType]?: any } & Record; type QueryWithHelpers = Query & THelpers; From ec781d560f8e0c556fb3e1d6305a3cc0407dce95 Mon Sep 17 00:00:00 2001 From: Sean Derrow Date: Mon, 26 Feb 2024 01:34:02 -0500 Subject: [PATCH 11/13] Lint --- types/query.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/types/query.d.ts b/types/query.d.ts index 1bfb4950647..f450182ffdb 100644 --- a/types/query.d.ts +++ b/types/query.d.ts @@ -39,7 +39,10 @@ declare module 'mongoose' { type MongooseBaseQueryOptions = MongooseQueryOptions; - type MongooseUpdateQueryOptions = MongooseQueryOptions; + type MongooseUpdateQueryOptions = MongooseQueryOptions< + DocType, + MongooseBaseQueryOptionKeys | "timestamps" + >; type ProjectionFields = { [Key in keyof DocType]?: any } & Record; From 4df404b1f4d143b79fc3eb40751b7f7525b1e27b Mon Sep 17 00:00:00 2001 From: Sean Derrow Date: Mon, 26 Feb 2024 02:02:16 -0500 Subject: [PATCH 12/13] More lint --- types/query.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/query.d.ts b/types/query.d.ts index f450182ffdb..6d53f4f473e 100644 --- a/types/query.d.ts +++ b/types/query.d.ts @@ -18,21 +18,21 @@ declare module 'mongoose' { type FilterQuery = _FilterQuery; type MongooseBaseQueryOptionKeys = - | "context" - | "multipleCastError" - | "overwriteDiscriminatorKey" - | "populate" - | "runValidators" - | "sanitizeProjection" - | "sanitizeFilter" - | "setDefaultsOnInsert" - | "strict" - | "strictQuery" - | "translateAliases"; + | 'context' + | 'multipleCastError' + | 'overwriteDiscriminatorKey' + | 'populate' + | 'runValidators' + | 'sanitizeProjection' + | 'sanitizeFilter' + | 'setDefaultsOnInsert' + | 'strict' + | 'strictQuery' + | 'translateAliases'; type MongooseQueryOptions< DocType = unknown, - Keys extends keyof QueryOptions = MongooseBaseQueryOptionKeys | "timestamps" | "lean" + Keys extends keyof QueryOptions = MongooseBaseQueryOptionKeys | 'timestamps' | 'lean' > = Pick, Keys> & { [other: string]: any; }; @@ -41,7 +41,7 @@ declare module 'mongoose' { type MongooseUpdateQueryOptions = MongooseQueryOptions< DocType, - MongooseBaseQueryOptionKeys | "timestamps" + MongooseBaseQueryOptionKeys | 'timestamps' >; type ProjectionFields = { [Key in keyof DocType]?: any } & Record; From 834c29f0cb73b8e4e4cfaf5a273831d0f135c15f Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 26 Feb 2024 15:11:58 -0500 Subject: [PATCH 13/13] chore: release 7.6.9 --- CHANGELOG.md | 7 +++++++ package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05ac8299cc9..4639ed8d7c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +7.6.9 / 2024-02-26 +================== + * fix(document): handle embedded recursive discriminators on nested path defined using Schema.prototype.discriminator #14256 #14245 + * types(model): correct return type for findByIdAndDelete() #14233 #14190 + * docs(connections): add note about using asPromise() with createConnection() for error handling #14364 #14266 + * docs(model+query+findoneandupdate): add more details about overwriteDiscriminatorKey option to docs #14264 #14246 + 7.6.8 / 2024-01-08 ================== * perf(schema): remove unnecessary lookahead in numeric subpath check diff --git a/package.json b/package.json index 3f6a5beb0a8..d36925cae48 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mongoose", "description": "Mongoose MongoDB ODM", - "version": "7.6.8", + "version": "7.6.9", "author": "Guillermo Rauch ", "keywords": [ "mongodb",