diff --git a/docs/migrating_to_10.md b/docs/migrating_to_10.md index 9f4f4044c63..bb027724f55 100644 --- a/docs/migrating_to_10.md +++ b/docs/migrating_to_10.md @@ -28,3 +28,18 @@ Cast values explicitly instead of relying on adhoc type casting. The function signature for `Document#set()` and its alias `Document#$set()` is now `function set(path, val, options?)` - the 3rd argument is now `options`. The `type` argument has been removed. + +## Removed support for passing a query to model query methods + +Mongoose 10 no longer supports passing a query instance as the filter to model query methods like `find()` and `findOne()`. + +If you need to copy a query into another query, use `Query.prototype.merge()`: + +```javascript +const query = User.find({ status: 'active' }).select('name'); +const queryToRun = User.find().merge(query); + +await queryToRun.exec(); +``` + +`Query.prototype.merge()` copies the query's conditions, field selection, and options to the query it is called on. diff --git a/lib/query.js b/lib/query.js index fcf397c7e2f..fb343df3527 100644 --- a/lib/query.js +++ b/lib/query.js @@ -3007,6 +3007,10 @@ Query.prototype.countDocuments = function(conditions, options) { if (canMerge(conditions)) { this.merge(conditions); + } else if (conditions != null) { + this.error( + new ObjectParameterError(conditions, 'filter', 'countDocuments') + ); } if (options != null) { @@ -3661,6 +3665,10 @@ Query.prototype.findOneAndDelete = function(filter, options) { if (canMerge(filter)) { this.merge(filter); + } else if (filter != null) { + this.error( + new ObjectParameterError(filter, 'filter', 'findOneAndDelete') + ); } options && this.setOptions(options); @@ -4468,9 +4476,8 @@ function _update(query, op, filter, doc, options) { query.op = op; doc = doc || {}; - if (!(filter instanceof Query) && - filter != null && - filter.toString() !== '[object Object]') { + if (filter instanceof Query || + (filter != null && filter.toString() !== '[object Object]')) { query.error(new ObjectParameterError(filter, 'filter', op)); } else { query.merge(filter); @@ -5766,8 +5773,7 @@ Query.prototype.model; */ function canMerge(value) { - return value instanceof Query || utils.isObject(value) || value === null; - + return (!(value instanceof Query) && utils.isObject(value)) || value === null; } /*! diff --git a/test/query.test.js b/test/query.test.js index e3237205f12..14034c97bb1 100644 --- a/test/query.test.js +++ b/test/query.test.js @@ -3000,6 +3000,45 @@ describe('Query', function() { assert.equal(res.owner.name, 'Val'); }); + + it('does not merge queries passed as a filter to find() and findOne()', async function() { + const Test = db.model('Test', new Schema({ name: String })); + + const q = Test.find({ name: 'foo' }); + + await assert.rejects( + Test.find(q).exec(), + /Parameter "filter" to find\(\) must be an object/ + ); + await assert.rejects( + Test.findOne(q).exec(), + /Parameter "filter" to findOne\(\) must be an object/ + ); + await assert.rejects( + Test.countDocuments(q).exec(), + /Parameter "filter" to countDocuments\(\) must be an object/ + ); + await assert.rejects( + Test.findOneAndDelete(q).exec(), + /Parameter "filter" to findOneAndDelete\(\) must be an object/ + ); + await assert.rejects( + Test.updateOne(q, { name: 'bar' }).exec(), + /Parameter "filter" to updateOne\(\) must be an object/ + ); + await assert.rejects( + Test.updateMany(q, { name: 'bar' }).exec(), + /Parameter "filter" to updateMany\(\) must be an object/ + ); + await assert.rejects( + Test.replaceOne(q, { name: 'bar' }).exec(), + /Parameter "filter" to replaceOne\(\) must be an object/ + ); + + // `merge()` still supports queries + const res = await Test.find().merge(q); + assert.deepStrictEqual(res, []); + }); }); describe('Query#validate() (gh-7984)', function() { diff --git a/test/types/models.test.ts b/test/types/models.test.ts index 1cd5a9c3294..35f4a5919a8 100644 --- a/test/types/models.test.ts +++ b/test/types/models.test.ts @@ -1,6 +1,5 @@ import mongoose, { AggregateOptions, - CallbackError, DeleteResult, Document, HydratedDocument, @@ -320,9 +319,6 @@ function find() { Project.find({}); Project.find({ name: 'Hello' }); - // just callback; this is no longer supported on .find() - Project.find((error: CallbackError, result: IProject[]) => console.log(error, result)); - // filter + projection Project.find({}, undefined); Project.find({}, null); @@ -790,6 +786,13 @@ async function gh13705() { const findOneAndUpdateResWithMetadata = await TestModel.findOneAndUpdate({}, {}, { lean: true, includeResultMetadata: true }); expect(findOneAndUpdateResWithMetadata).type.toBe>(); + + const findOneAndUpdateResWithMetadataAndOverride = await TestModel.findOneAndUpdate<{ answer: 42 }>( + {}, + {}, + { includeResultMetadata: true } + ); + expect(findOneAndUpdateResWithMetadataAndOverride).type.toBe>(); } async function gh16413() { diff --git a/test/types/queries.test.ts b/test/types/queries.test.ts index 3aa68c30c84..2bb367487e3 100644 --- a/test/types/queries.test.ts +++ b/test/types/queries.test.ts @@ -735,8 +735,8 @@ async function gh13142() { options: Options ): Promise< Options['lean'] extends true - ? Pick> | null - : HydratedDocument>> | null + ? mongoose.ApplyProjection | null + : HydratedDocument> | null > { return this.blogModel.findOne(filter, projection, options); } @@ -815,6 +815,29 @@ async function gh14190() { expect(res2).type.toBeAssignableTo< ModifyResult> >(); + + const res3 = await UserModel.find().findOneAndUpdate( + { name: 'test' }, + { name: 'updated' }, + { includeResultMetadata: true } + ); + expect(res3).type.toBeAssignableTo< + ModifyResult> + >(); + + const upserted = await UserModel.find().findOneAndUpdate( + { name: 'test' }, + { name: 'updated' }, + { upsert: true, new: true } + ); + expect(upserted).type.toBe>(); + + const upsertedById = await UserModel.find().findByIdAndUpdate( + '0'.repeat(24), + { name: 'updated' }, + { upsert: true, returnDocument: 'after' } + ); + expect(upsertedById).type.toBe>(); } function mongooseQueryOptions() { @@ -1061,11 +1084,6 @@ async function gh15779() { expect(v8Filter.age).type.toBeAssignableFrom(42); expect(v8Filter.age).type.not.toBeAssignableFrom('taco'); - const TestModel = model('Test', new Schema({ age: Number, name: String })); - const query = TestModel.find({ age: { $gt: 18 } }); - TestModel.find(query); // Should compile without errors - TestModel.findOne(query); - TestModel.deleteMany(query); } async function gh15786() { diff --git a/types/callback.d.ts b/types/callback.d.ts index 370379ab4bf..61f4db41180 100644 --- a/types/callback.d.ts +++ b/types/callback.d.ts @@ -1,8 +1,3 @@ declare module 'mongoose' { - type CallbackError = NativeError | null; - - type Callback = (error: CallbackError, result: T) => void; - - type CallbackWithoutResult = (error: CallbackError) => void; - type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void; + type CallbackWithoutResultAndOptionalError = (error?: NativeError | null) => void; } diff --git a/types/models.d.ts b/types/models.d.ts index c28d0f4de02..4f3d91ba55b 100644 --- a/types/models.d.ts +++ b/types/models.d.ts @@ -36,8 +36,10 @@ declare module 'mongoose' { skipValidation?: boolean; throwOnValidationError?: boolean; strict?: boolean | 'throw'; + /** When false, do not add timestamps to documents. Can be overridden at the operation level. */ timestamps?: boolean; + /** set to `false` to skip all user-defined middleware, or `{ pre: false }` / `{ post: false }` to skip only pre or post hooks */ middleware?: boolean | SkipMiddlewareOptions; } @@ -46,6 +48,7 @@ declare module 'mongoose' { timestamps?: boolean; session?: ClientSession; validateBeforeSave?: boolean; + /** set to `false` to skip all user-defined middleware, or `{ pre: false }` / `{ post: false }` to skip only pre or post hooks */ middleware?: boolean | SkipMiddlewareOptions; } @@ -77,6 +80,7 @@ declare module 'mongoose' { ordered?: boolean; lean?: boolean; throwOnValidationError?: boolean; + /** set to `false` to skip all user-defined middleware, or `{ pre: false }` / `{ post: false }` to skip only pre or post hooks */ middleware?: boolean | SkipMiddlewareOptions; timestamps?: boolean | QueryTimestampsConfig; @@ -92,6 +96,7 @@ declare module 'mongoose' { interface ModifyResult { value: Default__v> | null; + /** see https://www.mongodb.com/docs/manual/reference/command/findAndModify/#lasterrorobject */ lastErrorObject?: { updatedExisting?: boolean; @@ -116,6 +121,7 @@ declare module 'mongoose' { SessionOption { checkKeys?: boolean; j?: boolean; + /** An array of paths that tell mongoose to only validate and save the paths in `pathsToSave`. */ pathsToSave?: string[]; safe?: boolean | WriteConcern; @@ -124,6 +130,7 @@ declare module 'mongoose' { validateModifiedOnly?: boolean; w?: number | string; wtimeout?: number; + /** set to `false` to skip all user-defined middleware, or `{ pre: false }` / `{ post: false }` to skip only pre or post hooks */ middleware?: boolean | SkipMiddlewareOptions; } @@ -138,6 +145,7 @@ declare module 'mongoose' { interface MongooseBulkWritePerOperationOptions { /** Skip validation for this operation. */ skipValidation?: boolean; + /** When false, do not add timestamps. When true, overrides the `timestamps` option set in the `bulkWrite` options. */ timestamps?: boolean; } @@ -145,6 +153,7 @@ declare module 'mongoose' { interface MongooseBulkUpdatePerOperationOptions extends MongooseBulkWritePerOperationOptions { /** When true, allows updating fields that are marked as `immutable` in the schema. */ overwriteImmutable?: boolean; + /** When false, do not set default values on insert. */ setDefaultsOnInsert?: boolean; } @@ -216,59 +225,173 @@ declare module 'mongoose' { ObtainSchemaGeneric['lean'] : false; - /** - * Models are fancy constructors compiled from `Schema` definitions. - * An instance of a model is called a document. - * Models are responsible for creating and reading documents from the underlying MongoDB database - */ - export interface Model< + interface ModelDocumentMethods< TRawDocType, - TQueryHelpers = {}, - TInstanceMethods = {}, - TVirtuals = {}, - THydratedDocumentType = HydratedDocument, - TSchema = any, - TLeanResultType = TRawDocType> extends - NodeJS.EventEmitter, - IndexManager, - SessionStarter { - new >(doc?: DocType, fields?: any | null, options?: AnyObject): THydratedDocumentType; + TQueryHelpers, + TInstanceMethods, + TVirtuals, + THydratedDocumentType, + TSchema + > { + /** Creates a new document or documents */ + create(): Promise; + create(doc: Partial): Promise; + create(docs: Array>): Promise; + create(docs: Array>>>, options: CreateOptions & { aggregateErrors: true }): Promise<(THydratedDocumentType | Error)[]>; + create(docs: Array>>>, options?: CreateOptions): Promise; + create(doc: DeepPartial>>): Promise; + create(...docs: Array>>>): Promise; - aggregate(pipeline?: PipelineStage[], options?: AggregateOptions): Aggregate>; - aggregate(pipeline: PipelineStage[]): Aggregate>; + /** Adds a discriminator type. */ + discriminator>( + name: string | number, + schema: TDiscriminatorSchema, + value?: string | number | ObjectId | DiscriminatorOptions + ): Model< + TRawDocType & InferSchemaType, + TQueryHelpers & ObtainSchemaGeneric, + TInstanceMethods & ObtainSchemaGeneric, + TVirtuals & ObtainSchemaGeneric + > & ObtainSchemaGeneric & ObtainSchemaGeneric; + discriminator( + name: string | number, + schema: Schema, + value?: string | number | ObjectId | DiscriminatorOptions + ): Model; + discriminator( + name: string | number, + schema: Schema, + value?: string | number | ObjectId | DiscriminatorOptions + ): U; - /** Base Mongoose instance the model uses. */ - base: Mongoose; + /** + * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. + * The document returned has no paths marked as modified initially. + * With `strict: false`, fields not in the schema are kept on the document; pass + * `ExtraFields` to describe their types, e.g. + * `Model.hydrate<{ totalOrders: number }>(obj, null, { strict: false })`. + */ + hydrate( + obj: any, + projection: ProjectionType | null | undefined, + options: HydrateOptions & { strict: false } + ): THydratedDocumentType & ExtraFields; + hydrate(obj: any, projection?: ProjectionType | null | undefined, options?: HydrateOptions): THydratedDocumentType; - /** Standard Schema adapter for validating input with this model's schema. */ - readonly '~standard': StandardSchemaV1.Props< - Default__v< - Default_id>, - ObtainSchemaGeneric - > + /** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */ + insertMany( + docs: Array + ): Promise>; + insertMany( + doc: Array, + options: InsertManyOptions & { ordered: false; rawResult: true; } + ): Promise> & { + mongoose: { + validationErrors: (CastError | Error.ValidatorError)[]; + results: Array< + Error | + Object | + THydratedDocumentType + > + } + }>; + insertMany( + docs: Array, + options: InsertManyOptions & { lean: true, rawResult: true; } + ): Promise>>; + insertMany( + doc: DocContents | TRawDocType, + options: InsertManyOptions & { ordered: false; rawResult: true; } + ): Promise> & { + mongoose: { + validationErrors: (CastError | Error.ValidatorError)[]; + results: Array< + Error | + Object | + MergeType + > + } + }>; + insertMany( + docs: Array, + options: InsertManyOptions & { lean: true; } + ): Promise>>; + insertMany( + docs: Array, + options: InsertManyOptions & { rawResult: true; } + ): Promise>>; + insertMany( + docs: Array, + options: InsertManyOptions & { lean: true; } + ): Promise>>; + insertMany( + docs: Array, + options: InsertManyOptions & { rawResult: true; } + ): Promise>>; + insertMany( + doc: DocContents, + options: InsertManyOptions & { lean: true; } + ): Promise>>; + insertMany( + doc: DocContents, + options: InsertManyOptions & { rawResult: true; } + ): Promise>>; + insertMany( + doc: Array, + options: InsertManyOptions + ): Promise>; + insertMany( + docs: Array + ): Promise>>>; + insertMany( + doc: DocContents, + options: InsertManyOptions + ): Promise>>>; + insertMany( + docs: Array, + options: InsertManyOptions + ): Promise>>>; + insertMany( + doc: DocContents + ): Promise< + Array>> >; /** - * If this is a discriminator model, `baseModelName` is the name of - * the base model. + * Shortcut for saving one document to the database. + * `MyModel.insertOne(obj, options)` is almost equivalent to `new MyModel(obj).save(options)`. + * The difference is that `insertOne()` checks if `obj` is already a document, and checks for discriminators. */ - baseModelName: string | undefined; + insertOne(doc: Partial>, options?: SaveOptions): Promise; - /* Cast the given POJO to the model's schema */ - castObject(obj: AnyObject, options?: { ignoreCastErrors?: boolean }): TRawDocType; + /** + * List all [Atlas search indexes](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) on this model's collection. + * This function only works when connected to MongoDB Atlas. + */ + listSearchIndexes(options?: mongodb.ListSearchIndexesOptions): Promise>; + + /** Populates document references. */ + populate( + docs: Array, + options: PopulateOptions | Array | string + ): Promise>; + populate( + doc: any, options: PopulateOptions | Array | string + ): Promise; + populate( + docs: Array, + options: PopulateOptions | Array | string + ): Promise, TRawDocType>>>; + populate( + doc: any, options: PopulateOptions | Array | string + ): Promise, TRawDocType>>; + aggregate(pipeline?: PipelineStage[], options?: AggregateOptions): Aggregate>; + aggregate(pipeline: PipelineStage[]): Aggregate>; /* Apply defaults to the given document or POJO. */ applyDefaults(obj: AnyObject): AnyObject; applyDefaults(obj: TRawDocType): TRawDocType; - /* Apply virtuals to the given POJO. */ - applyVirtuals(obj: AnyObject, virtalsToApply?: string[]): AnyObject; - - /** - * Apply this model's timestamps to a given POJO, including subdocument timestamps - */ - applyTimestamps(obj: AnyObject, options?: { isUpdate?: boolean, currentTime?: () => Date }): AnyObject; - /** * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one @@ -292,163 +415,105 @@ declare module 'mongoose' { */ bulkSave(documents: Array, options?: MongooseBulkSaveOptions): Promise; - /** Collection the model uses. */ - collection: Collection; + /** Casts and validates the given object against this model's schema, returning the casted-and-validated copy of `obj`, passing the given `context` to custom validators. */ + validate(): Promise; + validate(obj: any): Promise; + validate(obj: any, pathsOrOptions: PathsToValidate): Promise; + validate(obj: any, pathsOrOptions: { pathsToSkip?: pathsToSkip }): Promise; + } - /** Creates a `countDocuments` query: counts the number of documents that match `filter`. */ - countDocuments( - filter?: QueryFilter, - options?: (mongodb.CountOptions & MongooseBaseQueryOptions & mongodb.Abortable) | null + interface ModelQueryMethods< + TRawDocType, + TQueryHelpers, + TInstanceMethods, + TVirtuals, + THydratedDocumentType, + TSchema, + TLeanResultType + > { + /** + * Finds a single document by its _id field. `findById(id)` is almost* + * equivalent to `findOne({ _id: id })`. If you want to query by a document's + * `_id`, use `findById()` instead of `findOne()`. + */ + findById>( + id: any, + projection: Projection, + options: QueryOptions & { lean: true } ): QueryWithHelpers< - number, + ApplyProjection | null, THydratedDocumentType, TQueryHelpers, - TRawDocType, - 'countDocuments', + TLeanResultType, + 'findOne', TInstanceMethods & TVirtuals >; - countDocuments( - filter?: Query, - options?: (mongodb.CountOptions & MongooseBaseQueryOptions & mongodb.Abortable) | null + findById( + id: any, + projection: ProjectionType | null | undefined, + options: QueryOptions & { lean: true } ): QueryWithHelpers< - number, - THydratedDocumentType, + TLeanResultType | null, + ResultDoc, TQueryHelpers, - TRawDocType, - 'countDocuments', + TLeanResultType, + 'findOne', TInstanceMethods & TVirtuals >; - - /** Creates a new document or documents */ - create(): Promise; - create(doc: Partial): Promise; - create(docs: Array>): Promise; - create(docs: Array>>>, options: CreateOptions & { aggregateErrors: true }): Promise<(THydratedDocumentType | Error)[]>; - create(docs: Array>>>, options?: CreateOptions): Promise; - create(doc: DeepPartial>>): Promise; - create(...docs: Array>>>): Promise; - - /** - * Create the collection for this model. By default, if no indexes are specified, - * mongoose will not create the collection for the model until any documents are - * created. Use this method to create the collection explicitly. - */ - createCollection(options?: mongodb.CreateCollectionOptions & Pick & { middleware?: boolean | SkipMiddlewareOptions }): Promise>; - - /** - * Create an [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/). - * This function only works when connected to MongoDB Atlas. - */ - createSearchIndex(description: SearchIndexDescription): Promise; - - /** - * Creates all [Atlas search indexes](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) defined in this model's schema. - * This function only works when connected to MongoDB Atlas. - */ - createSearchIndexes(): Promise; - - /** Connection the model uses. */ - db: Connection; - - /** - * Deletes all of the documents that match `conditions` from the collection. - * Behaves like `remove()`, but deletes all documents that match `conditions` - * regardless of the `single` option. - */ - deleteMany( - filter?: QueryFilter, - options?: (mongodb.DeleteOptions & MongooseBaseQueryOptions) | null + findById( + id: any, + projection: ProjectionType | null | undefined, + options: QueryOptions & { lean: false } ): QueryWithHelpers< - mongodb.DeleteResult, - THydratedDocumentType, + ResultDoc | null, + ResultDoc, TQueryHelpers, TLeanResultType, - 'deleteMany', + 'findOne', TInstanceMethods & TVirtuals >; - deleteMany( - filter?: Query, - options?: (mongodb.DeleteOptions & MongooseBaseQueryOptions) | null + findById( + id?: any, + projection?: ProjectionType | null | undefined, + options?: QueryOptions | null ): QueryWithHelpers< - mongodb.DeleteResult, - THydratedDocumentType, + HasLeanOption extends true ? TLeanResultType | null : ResultDoc | null, + ResultDoc, TQueryHelpers, TLeanResultType, - 'deleteMany', + 'findOne', TInstanceMethods & TVirtuals >; - /** - * Deletes the first document that matches `conditions` from the collection. - * Behaves like `remove()`, but deletes at most one document regardless of the - * `single` option. - */ - deleteOne( - filter?: QueryFilter, - options?: (mongodb.DeleteOptions & MongooseBaseQueryOptions) | null + /** Finds one document. */ + findOne>( + filter: QueryFilter, + projection: Projection, + options?: QueryOptions & { lean?: false } & mongodb.Abortable ): QueryWithHelpers< - mongodb.DeleteResult, + ProjectedHydratedDocument | null, THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'deleteOne', + 'findOne', TInstanceMethods & TVirtuals >; - deleteOne( - filter?: Query, - options?: (mongodb.DeleteOptions & MongooseBaseQueryOptions) | null + findOne>( + filter: QueryFilter, + projection: undefined | null, + options: QueryOptions & { projection: Projection; lean?: false } & mongodb.Abortable ): QueryWithHelpers< - mongodb.DeleteResult, + ProjectedHydratedDocument | null, THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'deleteOne', + 'findOne', TInstanceMethods & TVirtuals >; - - /** Adds a discriminator type. */ - discriminator>( - name: string | number, - schema: TDiscriminatorSchema, - value?: string | number | ObjectId | DiscriminatorOptions - ): Model< - TRawDocType & InferSchemaType, - TQueryHelpers & ObtainSchemaGeneric, - TInstanceMethods & ObtainSchemaGeneric, - TVirtuals & ObtainSchemaGeneric - > & ObtainSchemaGeneric & ObtainSchemaGeneric; - discriminator( - name: string | number, - schema: Schema, - value?: string | number | ObjectId | DiscriminatorOptions - ): Model; - discriminator( - name: string | number, - schema: Schema, - value?: string | number | ObjectId | DiscriminatorOptions - ): U; - - /** - * Delete an existing [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) by name. - * This function only works when connected to MongoDB Atlas. - */ - dropSearchIndex(name: string): Promise; - - /** - * Event emitter that reports any errors that occurred. Useful for global error - * handling. - */ - events: NodeJS.EventEmitter; - - /** - * Finds a single document by its _id field. `findById(id)` is almost* - * equivalent to `findOne({ _id: id })`. If you want to query by a document's - * `_id`, use `findById()` instead of `findOne()`. - */ - findById>( - id: any, + findOne>( + filter: QueryFilter, projection: Projection, - options: QueryOptions & { lean: true } + options: QueryOptions & { lean: true } & mongodb.Abortable ): QueryWithHelpers< ApplyProjection | null, THydratedDocumentType, @@ -457,10 +522,22 @@ declare module 'mongoose' { 'findOne', TInstanceMethods & TVirtuals >; - findById( - id: any, + findOne>( + filter: QueryFilter, + projection: undefined | null, + options: QueryOptions & { projection: Projection; lean: true } & mongodb.Abortable + ): QueryWithHelpers< + ApplyProjection | null, + THydratedDocumentType, + TQueryHelpers, + TLeanResultType, + 'findOne', + TInstanceMethods & TVirtuals + >; + findOne( + filter: QueryFilter, projection: ProjectionType | null | undefined, - options: QueryOptions & { lean: true } + options: QueryOptions & { lean: true } & mongodb.Abortable ): QueryWithHelpers< TLeanResultType | null, ResultDoc, @@ -469,10 +546,10 @@ declare module 'mongoose' { 'findOne', TInstanceMethods & TVirtuals >; - findById( - id: any, + findOne( + filter: QueryFilter, projection: ProjectionType | null | undefined, - options: QueryOptions & { lean: false } + options: QueryOptions & { lean: false } & mongodb.Abortable ): QueryWithHelpers< ResultDoc | null, ResultDoc, @@ -481,10 +558,10 @@ declare module 'mongoose' { 'findOne', TInstanceMethods & TVirtuals >; - findById( - id?: any, + findOne( + filter?: QueryFilter, projection?: ProjectionType | null | undefined, - options?: QueryOptions | null + options?: QueryOptions & mongodb.Abortable | null | undefined ): QueryWithHelpers< HasLeanOption extends true ? TLeanResultType | null : ResultDoc | null, ResultDoc, @@ -494,493 +571,124 @@ declare module 'mongoose' { TInstanceMethods & TVirtuals >; - /** Finds one document. */ - findOne>( + /** Creates a `find` query: gets a list of documents that match `filter`. */ + find>( filter: QueryFilter, projection: Projection, options?: QueryOptions & { lean?: false } & mongodb.Abortable ): QueryWithHelpers< - ProjectedHydratedDocument | null, + ProjectedHydratedDocument[], THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOne', + 'find', TInstanceMethods & TVirtuals >; - findOne>( + find>( filter: QueryFilter, projection: undefined | null, options: QueryOptions & { projection: Projection; lean?: false } & mongodb.Abortable ): QueryWithHelpers< - ProjectedHydratedDocument | null, + ProjectedHydratedDocument[], THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOne', + 'find', TInstanceMethods & TVirtuals >; - findOne>( + find>( filter: QueryFilter, projection: Projection, options: QueryOptions & { lean: true } & mongodb.Abortable ): QueryWithHelpers< - ApplyProjection | null, + ApplyProjection[], THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOne', + 'find', TInstanceMethods & TVirtuals >; - findOne>( + find>( filter: QueryFilter, projection: undefined | null, options: QueryOptions & { projection: Projection; lean: true } & mongodb.Abortable ): QueryWithHelpers< - ApplyProjection | null, + ApplyProjection[], THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOne', + 'find', TInstanceMethods & TVirtuals >; - findOne( + find( filter: QueryFilter, projection: ProjectionType | null | undefined, options: QueryOptions & { lean: true } & mongodb.Abortable ): QueryWithHelpers< - TLeanResultType | null, + GetLeanResultType, ResultDoc, TQueryHelpers, TLeanResultType, - 'findOne', - TInstanceMethods & TVirtuals - >; - findOne( - filter: Query, - projection: ProjectionType | null | undefined, - options: QueryOptions & { lean: true } & mongodb.Abortable - ): QueryWithHelpers< - TLeanResultType | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOne', + 'find', TInstanceMethods & TVirtuals >; - findOne( + find( filter: QueryFilter, projection: ProjectionType | null | undefined, options: QueryOptions & { lean: false } & mongodb.Abortable ): QueryWithHelpers< - ResultDoc | null, + ResultDoc[], ResultDoc, TQueryHelpers, TLeanResultType, - 'findOne', + 'find', TInstanceMethods & TVirtuals >; - findOne( + find( filter?: QueryFilter, projection?: ProjectionType | null | undefined, - options?: QueryOptions & mongodb.Abortable | null | undefined + options?: QueryOptions & mongodb.Abortable ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType | null : ResultDoc | null, + HasLeanOption extends true ? TLeanResultType[] : ResultDoc[], ResultDoc, TQueryHelpers, TLeanResultType, - 'findOne', + 'find', TInstanceMethods & TVirtuals >; - findOne( - filter?: Query, - projection?: ProjectionType | null | undefined, - options?: QueryOptions & mongodb.Abortable | null | undefined + + /** Finds documents and counts the number of documents matching `filter`. */ + findAndCount>( + filter: QueryFilter, + projection: Projection, + options: QueryOptions & { sort: any; limit: number; lean: true } & mongodb.Abortable + ): Promise<[ApplyProjection[], number]>; + findAndCount( + filter: QueryFilter, + projection: ProjectionType | null | undefined, + options: QueryOptions & { sort: any; limit: number; lean: true } & mongodb.Abortable + ): Promise<[GetLeanResultType, number]>; + findAndCount( + filter: QueryFilter, + projection: ProjectionType | null | undefined, + options: QueryOptions & { sort: any; limit: number; lean: false } & mongodb.Abortable + ): Promise<[ResultDoc[], number]>; + findAndCount( + filter: QueryFilter, + projection: ProjectionType | null | undefined, + options: QueryOptions & { sort: any; limit: number } & mongodb.Abortable + ): Promise<[HasLeanOption extends true ? TLeanResultType[] : ResultDoc[], number]>; + + /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */ + findByIdAndDelete>( + id: mongodb.ObjectId | any, + options: QueryOptions & { projection: Projection; lean: true; includeResultMetadata?: false } ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType | null : THydratedDocumentType | null, + ApplyProjection | null, THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOne', - TInstanceMethods & TVirtuals - >; - - /** - * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. - * The document returned has no paths marked as modified initially. - * With `strict: false`, fields not in the schema are kept on the document; pass - * `ExtraFields` to describe their types, e.g. - * `Model.hydrate<{ totalOrders: number }>(obj, null, { strict: false })`. - */ - hydrate( - obj: any, - projection: ProjectionType | null | undefined, - options: HydrateOptions & { strict: false } - ): THydratedDocumentType & ExtraFields; - hydrate(obj: any, projection?: ProjectionType | null | undefined, options?: HydrateOptions): THydratedDocumentType; - - /** - * This function is responsible for building [indexes](https://www.mongodb.com/docs/manual/indexes/), - * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. - * Mongoose calls this function automatically when a model is created using - * [`mongoose.model()`](/docs/api/mongoose.html#mongoose_Mongoose-model) or - * [`connection.model()`](/docs/api/connection.html#connection_Connection-model), so you - * don't need to call it. - */ - init(): Promise; - - /** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */ - insertMany( - docs: Array - ): Promise>; - insertMany( - doc: Array, - options: InsertManyOptions & { ordered: false; rawResult: true; } - ): Promise> & { - mongoose: { - validationErrors: (CastError | Error.ValidatorError)[]; - results: Array< - Error | - Object | - THydratedDocumentType - > - } - }>; - insertMany( - docs: Array, - options: InsertManyOptions & { lean: true, rawResult: true; } - ): Promise>>; - insertMany( - doc: DocContents | TRawDocType, - options: InsertManyOptions & { ordered: false; rawResult: true; } - ): Promise> & { - mongoose: { - validationErrors: (CastError | Error.ValidatorError)[]; - results: Array< - Error | - Object | - MergeType - > - } - }>; - insertMany( - docs: Array, - options: InsertManyOptions & { lean: true; } - ): Promise>>; - insertMany( - docs: Array, - options: InsertManyOptions & { rawResult: true; } - ): Promise>>; - insertMany( - docs: Array, - options: InsertManyOptions & { lean: true; } - ): Promise>>; - insertMany( - docs: Array, - options: InsertManyOptions & { rawResult: true; } - ): Promise>>; - insertMany( - doc: DocContents, - options: InsertManyOptions & { lean: true; } - ): Promise>>; - insertMany( - doc: DocContents, - options: InsertManyOptions & { rawResult: true; } - ): Promise>>; - insertMany( - doc: Array, - options: InsertManyOptions - ): Promise>; - insertMany( - docs: Array - ): Promise>>>; - insertMany( - doc: DocContents, - options: InsertManyOptions - ): Promise>>>; - insertMany( - docs: Array, - options: InsertManyOptions - ): Promise>>>; - insertMany( - doc: DocContents - ): Promise< - Array>> - >; - - /** - * Shortcut for saving one document to the database. - * `MyModel.insertOne(obj, options)` is almost equivalent to `new MyModel(obj).save(options)`. - * The difference is that `insertOne()` checks if `obj` is already a document, and checks for discriminators. - */ - insertOne(doc: Partial>, options?: SaveOptions): Promise; - - /** - * List all [Atlas search indexes](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) on this model's collection. - * This function only works when connected to MongoDB Atlas. - */ - listSearchIndexes(options?: mongodb.ListSearchIndexesOptions): Promise>; - - /** The name of the model */ - modelName: string; - - /** Populates document references. */ - populate( - docs: Array, - options: PopulateOptions | Array | string - ): Promise>; - populate( - doc: any, options: PopulateOptions | Array | string - ): Promise; - populate( - docs: Array, - options: PopulateOptions | Array | string - ): Promise, TRawDocType>>>; - populate( - doc: any, options: PopulateOptions | Array | string - ): Promise, TRawDocType>>; - - /** - * Update an existing [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/). - * This function only works when connected to MongoDB Atlas. - */ - updateSearchIndex(name: string, definition: AnyObject): Promise; - - /** - * Changes the Connection instance this model uses to make requests to MongoDB. - * This function is most useful for changing the Connection that a Model defined using `mongoose.model()` uses - * after initialization. - */ - useConnection(connection: Connection): this; - - /** Casts and validates the given object against this model's schema, returning the casted-and-validated copy of `obj`, passing the given `context` to custom validators. */ - validate(): Promise; - validate(obj: any): Promise; - validate(obj: any, pathsOrOptions: PathsToValidate): Promise; - validate(obj: any, pathsOrOptions: { pathsToSkip?: pathsToSkip }): Promise; - - /** Watches the underlying collection for changes using [MongoDB change streams](https://www.mongodb.com/docs/manual/changeStreams/). */ - watch(pipeline?: Array>, options?: mongodb.ChangeStreamOptions & { hydrate?: boolean }): mongodb.ChangeStream; - - /** Adds a `$where` clause to this query */ - $where(argument: string | Function): QueryWithHelpers, THydratedDocumentType, TQueryHelpers, TRawDocType, 'find', TInstanceMethods & TVirtuals>; - - /** Registered discriminators for this model. */ - discriminators: { [name: string]: Model } | undefined; - - /** Translate any aliases fields/conditions so the final query or document object is pure */ - translateAliases(raw: any): any; - - /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */ - distinct( - field: DocKey, - filter?: QueryFilter, - options?: QueryOptions - ): QueryWithHelpers< - Array< - DocKey extends keyof WithLevel1NestedPaths - ? WithoutUndefined[DocKey]>> - : unknown - >, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'distinct', - TInstanceMethods & TVirtuals - >; - distinct( - field: DocKey, - filter?: Query, - options?: QueryOptions - ): QueryWithHelpers< - Array< - DocKey extends keyof WithLevel1NestedPaths - ? WithoutUndefined[DocKey]>> - : unknown - >, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'distinct', - TInstanceMethods & TVirtuals - >; - - /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */ - estimatedDocumentCount(options?: QueryOptions): QueryWithHelpers< - number, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'estimatedDocumentCount', - TInstanceMethods & TVirtuals - >; - - /** - * Returns a document with its `_id` if at least one document exists in the database that matches - * the given `filter`, and `null` otherwise. - */ - exists( - filter: QueryFilter - ): QueryWithHelpers< - { _id: InferId } | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOne', - TInstanceMethods & TVirtuals - >; - exists( - filter: Query - ): QueryWithHelpers< - { _id: InferId } | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOne', - TInstanceMethods & TVirtuals - >; - - /** Creates a `find` query: gets a list of documents that match `filter`. */ - find>( - filter: QueryFilter, - projection: Projection, - options?: QueryOptions & { lean?: false } & mongodb.Abortable - ): QueryWithHelpers< - ProjectedHydratedDocument[], - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - find>( - filter: QueryFilter, - projection: undefined | null, - options: QueryOptions & { projection: Projection; lean?: false } & mongodb.Abortable - ): QueryWithHelpers< - ProjectedHydratedDocument[], - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - find>( - filter: QueryFilter, - projection: Projection, - options: QueryOptions & { lean: true } & mongodb.Abortable - ): QueryWithHelpers< - ApplyProjection[], - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - find>( - filter: QueryFilter, - projection: undefined | null, - options: QueryOptions & { projection: Projection; lean: true } & mongodb.Abortable - ): QueryWithHelpers< - ApplyProjection[], - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - find( - filter: QueryFilter, - projection: ProjectionType | null | undefined, - options: QueryOptions & { lean: true } & mongodb.Abortable - ): QueryWithHelpers< - GetLeanResultType, - ResultDoc, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - find( - filter: Query, - projection: ProjectionType | null | undefined, - options: QueryOptions & { lean: true } & mongodb.Abortable - ): QueryWithHelpers< - GetLeanResultType, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - find( - filter: QueryFilter, - projection: ProjectionType | null | undefined, - options: QueryOptions & { lean: false } & mongodb.Abortable - ): QueryWithHelpers< - ResultDoc[], - ResultDoc, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - find( - filter?: QueryFilter, - projection?: ProjectionType | null | undefined, - options?: QueryOptions & mongodb.Abortable - ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType[] : ResultDoc[], - ResultDoc, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - find( - filter?: Query, - projection?: ProjectionType | null | undefined, - options?: QueryOptions & mongodb.Abortable - ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType[] : THydratedDocumentType[], - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'find', - TInstanceMethods & TVirtuals - >; - - /** Finds documents and counts the number of documents matching `filter`. */ - findAndCount>( - filter: QueryFilter, - projection: Projection, - options: QueryOptions & { sort: any; limit: number; lean: true } & mongodb.Abortable - ): Promise<[ApplyProjection[], number]>; - findAndCount( - filter: QueryFilter, - projection: ProjectionType | null | undefined, - options: QueryOptions & { sort: any; limit: number; lean: true } & mongodb.Abortable - ): Promise<[GetLeanResultType, number]>; - findAndCount( - filter: QueryFilter, - projection: ProjectionType | null | undefined, - options: QueryOptions & { sort: any; limit: number; lean: false } & mongodb.Abortable - ): Promise<[ResultDoc[], number]>; - findAndCount( - filter: QueryFilter, - projection: ProjectionType | null | undefined, - options: QueryOptions & { sort: any; limit: number } & mongodb.Abortable - ): Promise<[HasLeanOption extends true ? TLeanResultType[] : ResultDoc[], number]>; - - /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */ - findByIdAndDelete>( - id: mongodb.ObjectId | any, - options: QueryOptions & { projection: Projection; lean: true; includeResultMetadata?: false } - ): QueryWithHelpers< - ApplyProjection | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndDelete', + 'findOneAndDelete', TInstanceMethods & TVirtuals >; findByIdAndDelete>( @@ -1050,7 +758,6 @@ declare module 'mongoose' { TInstanceMethods & TVirtuals >; - /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */ findByIdAndUpdate>( id: mongodb.ObjectId | any, @@ -1088,18 +795,6 @@ declare module 'mongoose' { 'findOneAndUpdate', TInstanceMethods & TVirtuals >; - findByIdAndUpdate( - filter: Query, - update: UpdateQuery, - options: QueryOptions & { includeResultMetadata: true, lean: true } - ): QueryWithHelpers< - ModifyResult, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndUpdate', - TInstanceMethods & TVirtuals - >; findByIdAndUpdate( id: mongodb.ObjectId | any, update: UpdateQuery, @@ -1217,17 +912,6 @@ declare module 'mongoose' { 'findOneAndDelete', TInstanceMethods & TVirtuals >; - findOneAndDelete( - filter: Query, - options: QueryOptions & { lean: true } - ): QueryWithHelpers< - TLeanResultType | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndDelete', - TInstanceMethods & TVirtuals - >; findOneAndDelete( filter: QueryFilter, options: QueryOptions & { lean: false } @@ -1239,17 +923,6 @@ declare module 'mongoose' { 'findOneAndDelete', TInstanceMethods & TVirtuals >; - findOneAndDelete( - filter: Query, - options: QueryOptions & { lean: false } - ): QueryWithHelpers< - THydratedDocumentType | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndDelete', - TInstanceMethods & TVirtuals - >; findOneAndDelete( filter: QueryFilter, options: QueryOptions & { includeResultMetadata: true } @@ -1261,17 +934,6 @@ declare module 'mongoose' { 'findOneAndDelete', TInstanceMethods & TVirtuals >; - findOneAndDelete( - filter: Query, - options: QueryOptions & { includeResultMetadata: true } - ): QueryWithHelpers< - HasLeanOption extends true ? ModifyResult : ModifyResult, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndDelete', - TInstanceMethods & TVirtuals - >; findOneAndDelete( filter?: QueryFilter | null, options?: QueryOptions | null @@ -1283,17 +945,6 @@ declare module 'mongoose' { 'findOneAndDelete', TInstanceMethods & TVirtuals >; - findOneAndDelete( - filter?: Query | null, - options?: QueryOptions | null - ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType | null : THydratedDocumentType | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndDelete', - TInstanceMethods & TVirtuals - >; /** Creates a `findOneAndReplace` query: atomically finds the given document and replaces it with `replacement`. */ findOneAndReplace>( @@ -1356,18 +1007,6 @@ declare module 'mongoose' { 'findOneAndReplace', TInstanceMethods & TVirtuals >; - findOneAndReplace( - filter: Query, - replacement: TRawDocType | AnyObject, - options: QueryOptions & { lean: true } - ): QueryWithHelpers< - TLeanResultType | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndReplace', - TInstanceMethods & TVirtuals - >; findOneAndReplace( filter: QueryFilter, replacement: TRawDocType | AnyObject, @@ -1380,18 +1019,6 @@ declare module 'mongoose' { 'findOneAndReplace', TInstanceMethods & TVirtuals >; - findOneAndReplace( - filter: Query, - replacement: TRawDocType | AnyObject, - options: QueryOptions & { lean: false } - ): QueryWithHelpers< - THydratedDocumentType | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndReplace', - TInstanceMethods & TVirtuals - >; findOneAndReplace( filter: QueryFilter, replacement: TRawDocType | AnyObject, @@ -1404,18 +1031,6 @@ declare module 'mongoose' { 'findOneAndReplace', TInstanceMethods & TVirtuals >; - findOneAndReplace( - filter: Query, - replacement: TRawDocType | AnyObject, - options: QueryOptions & { includeResultMetadata: true } - ): QueryWithHelpers< - HasLeanOption extends true ? ModifyResult : ModifyResult, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndReplace', - TInstanceMethods & TVirtuals - >; findOneAndReplace( filter: QueryFilter, replacement: TRawDocType | AnyObject, @@ -1428,18 +1043,6 @@ declare module 'mongoose' { 'findOneAndReplace', TInstanceMethods & TVirtuals >; - findOneAndReplace( - filter: Query, - replacement: TRawDocType | AnyObject, - options: QueryOptions & { upsert: true } & ReturnsNewDoc - ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType : THydratedDocumentType, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndReplace', - TInstanceMethods & TVirtuals - >; findOneAndReplace( filter?: QueryFilter, replacement?: TRawDocType | AnyObject, @@ -1452,18 +1055,6 @@ declare module 'mongoose' { 'findOneAndReplace', TInstanceMethods & TVirtuals >; - findOneAndReplace( - filter?: Query, - replacement?: TRawDocType | AnyObject, - options?: QueryOptions | null - ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType | null : THydratedDocumentType | null, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndReplace', - TInstanceMethods & TVirtuals - >; /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */ findOneAndUpdate>( @@ -1526,18 +1117,6 @@ declare module 'mongoose' { 'findOneAndUpdate', TInstanceMethods & TVirtuals >; - findOneAndUpdate( - filter: Query, - update: UpdateQuery, - options: QueryOptions & { includeResultMetadata: true, lean: true } - ): QueryWithHelpers< - ModifyResult, - THydratedDocumentType, - TQueryHelpers, - TLeanResultType, - 'findOneAndUpdate', - TInstanceMethods & TVirtuals - >; findOneAndUpdate( filter: QueryFilter, update: UpdateQuery, @@ -1550,13 +1129,13 @@ declare module 'mongoose' { 'findOneAndUpdate', TInstanceMethods & TVirtuals >; - findOneAndUpdate( - filter: Query, + findOneAndUpdate( + filter: QueryFilter, update: UpdateQuery, - options: QueryOptions & { lean: true } + options: QueryOptions & { lean: false } ): QueryWithHelpers< - GetLeanResultType | null, - THydratedDocumentType, + ResultDoc | null, + ResultDoc, TQueryHelpers, TLeanResultType, 'findOneAndUpdate', @@ -1565,97 +1144,127 @@ declare module 'mongoose' { findOneAndUpdate( filter: QueryFilter, update: UpdateQuery, - options: QueryOptions & { lean: false } + options: QueryOptions & { includeResultMetadata: true } ): QueryWithHelpers< - ResultDoc | null, + HasLeanOption extends true ? ModifyResult : ModifyResult, ResultDoc, TQueryHelpers, TLeanResultType, 'findOneAndUpdate', TInstanceMethods & TVirtuals >; - findOneAndUpdate( - filter: Query, + findOneAndUpdate( + filter: QueryFilter, update: UpdateQuery, - options: QueryOptions & { lean: false } + options: QueryOptions & { upsert: true } & ReturnsNewDoc ): QueryWithHelpers< - THydratedDocumentType | null, - THydratedDocumentType, + HasLeanOption extends true ? TLeanResultType : ResultDoc, + ResultDoc, TQueryHelpers, TLeanResultType, 'findOneAndUpdate', TInstanceMethods & TVirtuals >; findOneAndUpdate( - filter: QueryFilter, - update: UpdateQuery, - options: QueryOptions & { includeResultMetadata: true } + filter?: QueryFilter, + update?: UpdateQuery, + options?: QueryOptions | null ): QueryWithHelpers< - HasLeanOption extends true ? ModifyResult : ModifyResult, + HasLeanOption extends true ? TLeanResultType | null : ResultDoc | null, ResultDoc, TQueryHelpers, TLeanResultType, 'findOneAndUpdate', TInstanceMethods & TVirtuals >; - findOneAndUpdate( - filter: Query, - update: UpdateQuery, - options: QueryOptions & { includeResultMetadata: true } + + /** Creates a `countDocuments` query: counts the number of documents that match `filter`. */ + countDocuments( + filter?: QueryFilter, + options?: (mongodb.CountOptions & MongooseBaseQueryOptions & mongodb.Abortable) | null ): QueryWithHelpers< - HasLeanOption extends true ? ModifyResult : ModifyResult, + number, THydratedDocumentType, TQueryHelpers, - TLeanResultType, - 'findOneAndUpdate', + TRawDocType, + 'countDocuments', TInstanceMethods & TVirtuals >; - findOneAndUpdate( - filter: QueryFilter, - update: UpdateQuery, - options: QueryOptions & { upsert: true } & ReturnsNewDoc + + /** + * Deletes all of the documents that match `conditions` from the collection. + * Behaves like `remove()`, but deletes all documents that match `conditions` + * regardless of the `single` option. + */ + deleteMany( + filter?: QueryFilter, + options?: (mongodb.DeleteOptions & MongooseBaseQueryOptions) | null ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType : ResultDoc, - ResultDoc, + mongodb.DeleteResult, + THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOneAndUpdate', + 'deleteMany', TInstanceMethods & TVirtuals >; - findOneAndUpdate( - filter: Query, - update: UpdateQuery, - options: QueryOptions & { upsert: true } & ReturnsNewDoc + + /** + * Deletes the first document that matches `conditions` from the collection. + * Behaves like `remove()`, but deletes at most one document regardless of the + * `single` option. + */ + deleteOne( + filter?: QueryFilter, + options?: (mongodb.DeleteOptions & MongooseBaseQueryOptions) | null ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType : THydratedDocumentType, + mongodb.DeleteResult, THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOneAndUpdate', + 'deleteOne', TInstanceMethods & TVirtuals >; - findOneAndUpdate( + + /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */ + distinct( + field: DocKey, filter?: QueryFilter, - update?: UpdateQuery, - options?: QueryOptions | null + options?: QueryOptions ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType | null : ResultDoc | null, - ResultDoc, + Array< + DocKey extends keyof WithLevel1NestedPaths + ? WithoutUndefined[DocKey]>> + : unknown + >, + THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOneAndUpdate', + 'distinct', TInstanceMethods & TVirtuals >; - findOneAndUpdate( - filter?: Query, - update?: UpdateQuery, - options?: QueryOptions | null + + /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */ + estimatedDocumentCount(options?: QueryOptions): QueryWithHelpers< + number, + THydratedDocumentType, + TQueryHelpers, + TLeanResultType, + 'estimatedDocumentCount', + TInstanceMethods & TVirtuals + >; + + /** + * Returns a document with its `_id` if at least one document exists in the database that matches + * the given `filter`, and `null` otherwise. + */ + exists( + filter: QueryFilter ): QueryWithHelpers< - HasLeanOption extends true ? TLeanResultType | null : ResultDoc | null, - ResultDoc, + { _id: InferId } | null, + THydratedDocumentType, TQueryHelpers, TLeanResultType, - 'findOneAndUpdate', + 'findOne', TInstanceMethods & TVirtuals >; @@ -1665,21 +1274,6 @@ declare module 'mongoose' { replacement?: TRawDocType | AnyObject, options?: (mongodb.ReplaceOptions & QueryOptions) | null ): QueryWithHelpers; - replaceOne( - filter?: Query, - replacement?: TRawDocType | AnyObject, - options?: (mongodb.ReplaceOptions & QueryOptions) | null - ): QueryWithHelpers; - - /** Apply changes made to this model's schema after this model was compiled. */ - recompileSchema(): void; - - /** Schema the model uses. */ - schema: IfAny< - TSchema, - Schema, TInstanceMethods, TQueryHelpers, TVirtuals>, - TSchema - >; /** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */ updateMany( @@ -1687,11 +1281,6 @@ declare module 'mongoose' { update: UpdateQuery | UpdateWithAggregationPipeline, options?: (mongodb.UpdateOptions & MongooseUpdateQueryOptions) | null ): QueryWithHelpers; - updateMany( - filter: Query, - update: UpdateQuery | UpdateWithAggregationPipeline, - options?: (mongodb.UpdateOptions & MongooseUpdateQueryOptions) | null - ): QueryWithHelpers; /** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */ updateOne( @@ -1699,11 +1288,6 @@ declare module 'mongoose' { update: UpdateQuery | UpdateWithAggregationPipeline, options?: (mongodb.UpdateOptions & MongooseUpdateQueryOptions) | null ): QueryWithHelpers; - updateOne( - filter: Query, - update: UpdateQuery | UpdateWithAggregationPipeline, - options?: (mongodb.UpdateOptions & MongooseUpdateQueryOptions) | null - ): QueryWithHelpers; /** Creates a Query, applies the passed conditions, and returns the Query. */ where( @@ -1726,6 +1310,143 @@ declare module 'mongoose' { 'find', TInstanceMethods & TVirtuals >; + } + + /** + * Models are fancy constructors compiled from `Schema` definitions. + * An instance of a model is called a document. + * Models are responsible for creating and reading documents from the underlying MongoDB database + */ + export interface Model< + TRawDocType, + TQueryHelpers = {}, + TInstanceMethods = {}, + TVirtuals = {}, + THydratedDocumentType = HydratedDocument, + TSchema = any, + TLeanResultType = TRawDocType> extends + NodeJS.EventEmitter, + ModelDocumentMethods, + ModelQueryMethods, + IndexManager, + SessionStarter { + new >(doc?: DocType, fields?: any | null, options?: AnyObject): THydratedDocumentType; + + /** Base Mongoose instance the model uses. */ + base: Mongoose; + + /** Standard Schema adapter for validating input with this model's schema. */ + readonly '~standard': StandardSchemaV1.Props< + Default__v< + Default_id>, + ObtainSchemaGeneric + > + >; + + /** + * If this is a discriminator model, `baseModelName` is the name of + * the base model. + */ + baseModelName: string | undefined; + + /* Cast the given POJO to the model's schema */ + castObject(obj: AnyObject, options?: { ignoreCastErrors?: boolean }): TRawDocType; + + + /* Apply virtuals to the given POJO. */ + applyVirtuals(obj: AnyObject, virtalsToApply?: string[]): AnyObject; + + /** + * Apply this model's timestamps to a given POJO, including subdocument timestamps + */ + applyTimestamps(obj: AnyObject, options?: { isUpdate?: boolean, currentTime?: () => Date }): AnyObject; + + + /** Collection the model uses. */ + collection: Collection; + + /** + * Create the collection for this model. By default, if no indexes are specified, + * mongoose will not create the collection for the model until any documents are + * created. Use this method to create the collection explicitly. + */ + createCollection(options?: mongodb.CreateCollectionOptions & Pick & { middleware?: boolean | SkipMiddlewareOptions }): Promise>; + + /** + * Create an [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/). + * This function only works when connected to MongoDB Atlas. + */ + createSearchIndex(description: SearchIndexDescription): Promise; + + /** + * Creates all [Atlas search indexes](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) defined in this model's schema. + * This function only works when connected to MongoDB Atlas. + */ + createSearchIndexes(): Promise; + + /** Connection the model uses. */ + db: Connection; + + /** + * Delete an existing [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) by name. + * This function only works when connected to MongoDB Atlas. + */ + dropSearchIndex(name: string): Promise; + + /** + * Event emitter that reports any errors that occurred. Useful for global error + * handling. + */ + events: NodeJS.EventEmitter; + + /** + * This function is responsible for building [indexes](https://www.mongodb.com/docs/manual/indexes/), + * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. + * Mongoose calls this function automatically when a model is created using + * [`mongoose.model()`](/docs/api/mongoose.html#mongoose_Mongoose-model) or + * [`connection.model()`](/docs/api/connection.html#connection_Connection-model), so you + * don't need to call it. + */ + init(): Promise; + + /** The name of the model */ + modelName: string; + + /** + * Update an existing [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/). + * This function only works when connected to MongoDB Atlas. + */ + updateSearchIndex(name: string, definition: AnyObject): Promise; + + /** + * Changes the Connection instance this model uses to make requests to MongoDB. + * This function is most useful for changing the Connection that a Model defined using `mongoose.model()` uses + * after initialization. + */ + useConnection(connection: Connection): this; + + + /** Watches the underlying collection for changes using [MongoDB change streams](https://www.mongodb.com/docs/manual/changeStreams/). */ + watch(pipeline?: Array>, options?: mongodb.ChangeStreamOptions & { hydrate?: boolean }): mongodb.ChangeStream; + + /** Adds a `$where` clause to this query */ + $where(argument: string | Function): QueryWithHelpers, THydratedDocumentType, TQueryHelpers, TRawDocType, 'find', TInstanceMethods & TVirtuals>; + + /** Registered discriminators for this model. */ + discriminators: { [name: string]: Model } | undefined; + + /** Translate any aliases fields/conditions so the final query or document object is pure */ + translateAliases(raw: any): any; + + /** Apply changes made to this model's schema after this model was compiled. */ + recompileSchema(): void; + + /** Schema the model uses. */ + schema: IfAny< + TSchema, + Schema, TInstanceMethods, TQueryHelpers, TVirtuals>, + TSchema + >; /** * If auto encryption is enabled, returns a ClientEncryption instance that is configured with the same settings that diff --git a/types/query.d.ts b/types/query.d.ts index 55ff02b26b8..d1efed79572 100644 --- a/types/query.d.ts +++ b/types/query.d.ts @@ -334,10 +334,6 @@ declare module 'mongoose' { criteria?: QueryFilter, options?: QueryOptions ): QueryWithHelpers; - countDocuments( - criteria?: Query, - options?: QueryOptions - ): QueryWithHelpers; /** * Returns a wrapper around a [mongodb driver cursor](https://mongodb.github.io/node-mongodb-native/7.0/classes/FindCursor.html). @@ -354,10 +350,6 @@ declare module 'mongoose' { filter?: QueryFilter, options?: QueryOptions ): QueryWithHelpers; - deleteMany( - filter?: Query, - options?: QueryOptions - ): QueryWithHelpers; deleteMany(filter: QueryFilter): QueryWithHelpers< any, DocType, @@ -366,14 +358,6 @@ declare module 'mongoose' { 'deleteMany', TDocOverrides >; - deleteMany(filter: Query): QueryWithHelpers< - any, - DocType, - THelpers, - RawDocType, - 'deleteMany', - TDocOverrides - >; deleteMany(): QueryWithHelpers; /** @@ -385,10 +369,6 @@ declare module 'mongoose' { filter?: QueryFilter, options?: QueryOptions ): QueryWithHelpers; - deleteOne( - filter?: Query, - options?: QueryOptions - ): QueryWithHelpers; deleteOne(filter: QueryFilter): QueryWithHelpers< any, DocType, @@ -397,14 +377,6 @@ declare module 'mongoose' { 'deleteOne', TDocOverrides >; - deleteOne(filter: Query): QueryWithHelpers< - any, - DocType, - THelpers, - RawDocType, - 'deleteOne', - TDocOverrides - >; deleteOne(): QueryWithHelpers; /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */ @@ -424,22 +396,6 @@ declare module 'mongoose' { 'distinct', TDocOverrides >; - distinct( - field: DocKey, - filter?: Query, - options?: QueryOptions - ): QueryWithHelpers< - Array< - DocKey extends keyof WithLevel1NestedPaths - ? WithoutUndefined[DocKey]>> - : ResultType - >, - DocType, - THelpers, - RawDocType, - 'distinct', - TDocOverrides - >; /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */ elemMatch(path: string, val: any): this; @@ -483,11 +439,6 @@ declare module 'mongoose' { projection?: ProjectionType | null, options?: QueryOptions | null ): QueryWithHelpers, DocType, THelpers, RawDocType, 'find', TDocOverrides>; - find( - filter?: Query, - projection?: ProjectionType | null, - options?: QueryOptions | null - ): QueryWithHelpers, DocType, THelpers, RawDocType, 'find', TDocOverrides>; /** Declares the query a findOne operation. When executed, returns the first found document. */ findOne( @@ -495,21 +446,12 @@ declare module 'mongoose' { projection?: ProjectionType | null, options?: QueryOptions | null ): QueryWithHelpers; - findOne( - filter?: Query, - projection?: ProjectionType | null, - options?: QueryOptions | null - ): QueryWithHelpers; /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */ findOneAndDelete( filter?: QueryFilter, options?: QueryOptions | null ): QueryWithHelpers; - findOneAndDelete( - filter?: Query, - options?: QueryOptions | null - ): QueryWithHelpers; /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */ findOneAndUpdate( @@ -517,31 +459,16 @@ declare module 'mongoose' { update: UpdateQuery, options: QueryOptions & { includeResultMetadata: true } ): QueryWithHelpers, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides>; - findOneAndUpdate( - filter: Query, - update: UpdateQuery, - options: QueryOptions & { includeResultMetadata: true } - ): QueryWithHelpers, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides>; findOneAndUpdate( filter: QueryFilter, update: UpdateQuery, options: QueryOptions & { upsert: true } & ReturnsNewDoc ): QueryWithHelpers; - findOneAndUpdate( - filter: Query, - update: UpdateQuery, - options: QueryOptions & { upsert: true } & ReturnsNewDoc - ): QueryWithHelpers; findOneAndUpdate( filter?: QueryFilter, update?: UpdateQuery, options?: QueryOptions | null ): QueryWithHelpers; - findOneAndUpdate( - filter?: Query, - update?: UpdateQuery, - options?: QueryOptions | null - ): QueryWithHelpers; /** Declares the query a findById operation. When executed, returns the document with the given `_id`. */ findById( @@ -848,11 +775,6 @@ declare module 'mongoose' { replacement?: DocType | AnyObject, options?: QueryOptions | null ): QueryWithHelpers; - replaceOne( - filter?: Query, - replacement?: DocType | AnyObject, - options?: QueryOptions | null - ): QueryWithHelpers; /** * Sets this query's `sanitizeProjection` option. With `sanitizeProjection()`, you can pass potentially untrusted user data to `.select()`. @@ -966,11 +888,6 @@ declare module 'mongoose' { update: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null ): QueryWithHelpers; - updateMany( - filter: Query, - update: UpdateQuery | UpdateWithAggregationPipeline, - options?: QueryOptions | null - ): QueryWithHelpers; /** * Declare and/or execute this query as an updateOne() operation. Same as @@ -981,11 +898,6 @@ declare module 'mongoose' { update: UpdateQuery | UpdateWithAggregationPipeline, options?: QueryOptions | null ): QueryWithHelpers; - updateOne( - filter: Query, - update: UpdateQuery | UpdateWithAggregationPipeline, - options?: QueryOptions | null - ): QueryWithHelpers; /** * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,