mongoose 6.1.7 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -74,8 +74,8 @@ declare module 'mongoose' {
74
74
  * the model's schema except the `_id` index, and build any indexes that
75
75
  * are in your schema but not in MongoDB.
76
76
  */
77
- export function syncIndexes(options?: Record<string, unknown>): Promise<Array<string>>;
78
- export function syncIndexes(options: Record<string, unknown> | null, callback: Callback<Array<string>>): void;
77
+ export function syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
78
+ export function syncIndexes(options: SyncIndexesOptions | null, callback: Callback<ConnectionSyncIndexesResult>): void;
79
79
 
80
80
  /* Tells `sanitizeFilter()` to skip the given object when filtering out potential query selector injection attacks.
81
81
  * Use this method when you have a known query selector that you want to use. */
@@ -165,6 +165,7 @@ declare module 'mongoose' {
165
165
  export const version: string;
166
166
 
167
167
  export type CastError = Error.CastError;
168
+ export type SyncIndexesError = Error.SyncIndexesError;
168
169
 
169
170
  type Mongoose = typeof mongoose;
170
171
 
@@ -442,14 +443,14 @@ declare module 'mongoose' {
442
443
  * the model's schema except the `_id` index, and build any indexes that
443
444
  * are in your schema but not in MongoDB.
444
445
  */
445
- syncIndexes(options?: Record<string, unknown>): Promise<Array<string>>;
446
- syncIndexes(options: Record<string, unknown> | null, callback: Callback<Array<string>>): void;
446
+ syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
447
+ syncIndexes(options: SyncIndexesOptions | null, callback: Callback<ConnectionSyncIndexesResult>): void;
447
448
 
448
449
  /**
449
450
  * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
450
451
  * in a transaction. Mongoose will commit the transaction if the
451
452
  * async function executes successfully and attempt to retry if
452
- * there was a retriable error.
453
+ * there was a retryable error.
453
454
  */
454
455
  transaction(fn: (session: mongodb.ClientSession) => Promise<any>): Promise<any>;
455
456
 
@@ -768,6 +769,12 @@ declare module 'mongoose' {
768
769
  toDrop: Array<any>
769
770
  }
770
771
 
772
+ interface ModifyResult<T> {
773
+ value: Require_id<T> | null;
774
+ lastErrorObject?: mongodb.Document;
775
+ ok: 0 | 1;
776
+ }
777
+
771
778
  export const Model: Model<any>;
772
779
  interface Model<T, TQueryHelpers = {}, TMethods = {}, TVirtuals = {}> extends NodeJS.EventEmitter, AcceptsDiscriminator {
773
780
  new<DocType = AnyKeys<T> & AnyObject>(doc?: DocType, fields?: any | null, options?: boolean | AnyObject): HydratedDocument<T, TMethods, TVirtuals>;
@@ -799,7 +806,7 @@ declare module 'mongoose' {
799
806
  * sending multiple `save()` calls because with `bulkSave()` there is only one
800
807
  * network round trip to the MongoDB server.
801
808
  */
802
- bulkSave(documents: Array<Document>): Promise<mongodb.BulkWriteResult>;
809
+ bulkSave(documents: Array<Document>, options?: mongodb.BulkWriteOptions): Promise<mongodb.BulkWriteResult>;
803
810
 
804
811
  /** Collection the model uses. */
805
812
  collection: Collection;
@@ -877,10 +884,10 @@ declare module 'mongoose' {
877
884
  * equivalent to `findOne({ _id: id })`. If you want to query by a document's
878
885
  * `_id`, use `findById()` instead of `findOne()`.
879
886
  */
880
- findById(id: any, projection?: any | null, options?: QueryOptions | null, callback?: Callback<HydratedDocument<T, TMethods, TVirtuals> | null>): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
887
+ findById<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(id: any, projection?: any | null, options?: QueryOptions | null, callback?: Callback<ResultDoc | null>): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
881
888
 
882
889
  /** Finds one document. */
883
- findOne(filter?: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: Callback<HydratedDocument<T, TMethods, TVirtuals> | null>): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
890
+ findOne<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: Callback<ResultDoc | null>): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
884
891
 
885
892
  /**
886
893
  * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
@@ -972,45 +979,45 @@ declare module 'mongoose' {
972
979
  estimatedDocumentCount(options?: QueryOptions, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
973
980
 
974
981
  /**
975
- * Returns true if at least one document exists in the database that matches
976
- * the given `filter`, and false otherwise.
982
+ * Returns a document with its `_id` if at least one document exists in the database that matches
983
+ * the given `filter`, and `null` otherwise.
977
984
  */
978
- exists(filter: FilterQuery<T>): Promise<boolean>;
979
- exists(filter: FilterQuery<T>, callback: Callback<boolean>): void;
985
+ exists(filter: FilterQuery<T>): QueryWithHelpers<Pick<Document<T>, '_id'> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
986
+ exists(filter: FilterQuery<T>, callback: Callback<Pick<Document<T>, '_id'> | null>): QueryWithHelpers<Pick<Document<T>, '_id'> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
980
987
 
981
988
  /** Creates a `find` query: gets a list of documents that match `filter`. */
982
- find(callback?: Callback<HydratedDocument<T, TMethods, TVirtuals>[]>): QueryWithHelpers<Array<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
983
- find(filter: FilterQuery<T>, callback?: Callback<T[]>): QueryWithHelpers<Array<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
984
- find(filter: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: Callback<HydratedDocument<T, TMethods, TVirtuals>[]>): QueryWithHelpers<Array<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
989
+ find<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
990
+ find<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter: FilterQuery<T>, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
991
+ find<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
985
992
 
986
993
  /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
987
- findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals> | null, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
994
+ findByIdAndDelete<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
988
995
 
989
996
  /** Creates a `findByIdAndRemove` query, filtering by the given `_id`. */
990
- findByIdAndRemove(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals> | null, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
997
+ findByIdAndRemove<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
991
998
 
992
999
  /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
993
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<mongodb.ModifyResult<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
994
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals>, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
995
- findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals> | null, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
996
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<T>, callback: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals> | null, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1000
+ findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
1001
+ findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
1002
+ findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(id?: mongodb.ObjectId | any, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
1003
+ findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, callback: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
997
1004
 
998
1005
  /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
999
- findOneAndDelete(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals> | null, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1006
+ findOneAndDelete<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
1000
1007
 
1001
1008
  /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
1002
- findOneAndRemove(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals> | null, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1009
+ findOneAndRemove<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
1003
1010
 
1004
1011
  /** Creates a `findOneAndReplace` query: atomically finds the given document and replaces it with `replacement`. */
1005
- findOneAndReplace(filter: FilterQuery<T>, replacement: T | AnyObject, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals>, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1006
- findOneAndReplace(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals> | null, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1012
+ findOneAndReplace<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter: FilterQuery<T>, replacement: T | AnyObject, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
1013
+ findOneAndReplace<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
1007
1014
 
1008
1015
  /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
1009
- findOneAndUpdate(filter: FilterQuery<T>, update: UpdateQuery<T>, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<mongodb.ModifyResult<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1010
- findOneAndUpdate(filter: FilterQuery<T>, update: UpdateQuery<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: HydratedDocument<T, TMethods, TVirtuals>, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1011
- findOneAndUpdate(filter?: FilterQuery<T>, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: T | null, res: any) => void): QueryWithHelpers<HydratedDocument<T, TMethods, TVirtuals> | null, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1016
+ findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter: FilterQuery<T>, update: UpdateQuery<T>, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
1017
+ findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter: FilterQuery<T>, update: UpdateQuery<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
1018
+ findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: T | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
1012
1019
 
1013
- geoSearch(filter?: FilterQuery<T>, options?: GeoSearchOptions, callback?: Callback<Array<HydratedDocument<T, TMethods, TVirtuals>>>): QueryWithHelpers<Array<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1020
+ geoSearch<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, options?: GeoSearchOptions, callback?: Callback<Array<ResultDoc>>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
1014
1021
 
1015
1022
  /** Executes a mapReduce command. */
1016
1023
  mapReduce<Key, Value>(
@@ -1018,11 +1025,11 @@ declare module 'mongoose' {
1018
1025
  callback?: Callback
1019
1026
  ): Promise<any>;
1020
1027
 
1021
- remove(filter?: any, callback?: CallbackWithoutResult): QueryWithHelpers<any, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1028
+ remove<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: any, callback?: CallbackWithoutResult): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
1022
1029
 
1023
1030
  /** Creates a `replaceOne` query: finds the first document that matches `filter` and replaces it with `replacement`. */
1024
- replaceOne(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<any, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1025
- replaceOne(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<any, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1031
+ replaceOne<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
1032
+ replaceOne<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
1026
1033
 
1027
1034
  /** Schema the model uses. */
1028
1035
  schema: Schema<T>;
@@ -1031,18 +1038,18 @@ declare module 'mongoose' {
1031
1038
  * @deprecated use `updateOne` or `updateMany` instead.
1032
1039
  * Creates a `update` query: updates one or many documents that match `filter` with `update`, based on the `multi` option.
1033
1040
  */
1034
- update(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1041
+ update<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
1035
1042
 
1036
1043
  /** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */
1037
- updateMany(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1044
+ updateMany<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
1038
1045
 
1039
1046
  /** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */
1040
- updateOne(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1047
+ updateOne<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
1041
1048
 
1042
1049
  /** Creates a Query, applies the passed conditions, and returns the Query. */
1043
- where(path: string, val?: any): QueryWithHelpers<Array<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1044
- where(obj: object): QueryWithHelpers<Array<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1045
- where(): QueryWithHelpers<Array<HydratedDocument<T, TMethods, TVirtuals>>, HydratedDocument<T, TMethods, TVirtuals>, TQueryHelpers, T>;
1050
+ where<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(path: string, val?: any): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
1051
+ where<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(obj: object): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
1052
+ where<ResultDoc = HydratedDocument<T, TMethods, TVirtuals>>(): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
1046
1053
  }
1047
1054
 
1048
1055
  type UpdateWriteOpResult = mongodb.UpdateResult;
@@ -1505,6 +1512,11 @@ declare module 'mongoose' {
1505
1512
  * optimistic concurrency.
1506
1513
  */
1507
1514
  optimisticConcurrency?: boolean;
1515
+ /**
1516
+ * If `plugin()` called with tags, Mongoose will only apply plugins to schemas that have
1517
+ * a matching tag in `pluginTags`
1518
+ */
1519
+ pluginTags?: string[];
1508
1520
  /**
1509
1521
  * Allows setting query#read options at the schema level, providing us a way to apply default ReadPreferences
1510
1522
  * to all queries derived from a model.
@@ -2124,6 +2136,9 @@ declare module 'mongoose' {
2124
2136
  type QueryWithHelpers<ResultType, DocType, THelpers = {}, RawDocType = DocType> = Query<ResultType, DocType, THelpers, RawDocType> & THelpers;
2125
2137
 
2126
2138
  type UnpackedIntersection<T, U> = T extends (infer V)[] ? (V & U)[] : T & U;
2139
+ type UnpackedIntersectionWithNull<T, U> = T extends null ? UnpackedIntersection<T, U> | null : UnpackedIntersection<T, U>;
2140
+
2141
+ type ProjectionFields<DocType> = {[Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any} & Record<string, any>;
2127
2142
 
2128
2143
  class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
2129
2144
  _mongooseOptions: MongooseQueryOptions;
@@ -2268,9 +2283,24 @@ declare module 'mongoose' {
2268
2283
  findOneAndRemove(filter?: FilterQuery<DocType>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
2269
2284
 
2270
2285
  /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
2271
- findOneAndUpdate(filter: FilterQuery<DocType>, update: UpdateQuery<DocType>, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: DocType | null, res: mongodb.ModifyResult<DocType>) => void): QueryWithHelpers<mongodb.ModifyResult<DocType>, DocType, THelpers, RawDocType>;
2272
- findOneAndUpdate(filter: FilterQuery<DocType>, update: UpdateQuery<DocType>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: DocType, res: mongodb.ModifyResult<DocType>) => void): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
2273
- findOneAndUpdate(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: mongodb.ModifyResult<DocType>) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
2286
+ findOneAndUpdate(
2287
+ filter: FilterQuery<DocType>,
2288
+ update: UpdateQuery<DocType>,
2289
+ options: QueryOptions & { rawResult: true },
2290
+ callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
2291
+ ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType>;
2292
+ findOneAndUpdate(
2293
+ filter: FilterQuery<DocType>,
2294
+ update: UpdateQuery<DocType>,
2295
+ options: QueryOptions & { upsert: true } & ReturnsNewDoc,
2296
+ callback?: (err: CallbackError, doc: DocType, res: ModifyResult<DocType>) => void
2297
+ ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
2298
+ findOneAndUpdate(
2299
+ filter?: FilterQuery<DocType>,
2300
+ update?: UpdateQuery<DocType>,
2301
+ options?: QueryOptions | null,
2302
+ callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
2303
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
2274
2304
 
2275
2305
  /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
2276
2306
  findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
@@ -2407,11 +2437,13 @@ declare module 'mongoose' {
2407
2437
  polygon(path: string, ...coordinatePairs: number[][]): this;
2408
2438
 
2409
2439
  /** Specifies paths which should be populated with other documents. */
2410
- populate<Paths = {}>(path: string | any, select?: string | any, model?: string | Model<any, THelpers>, match?: any): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, RawDocType>;
2411
- populate<Paths = {}>(options: PopulateOptions | Array<PopulateOptions>): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, RawDocType>;
2440
+ populate<Paths = {}>(path: string | any, select?: string | any, model?: string | Model<any, THelpers>, match?: any): QueryWithHelpers<UnpackedIntersectionWithNull<ResultType, Paths>, DocType, THelpers, RawDocType>;
2441
+ populate<Paths = {}>(options: PopulateOptions | Array<PopulateOptions>): QueryWithHelpers<UnpackedIntersectionWithNull<ResultType, Paths>, DocType, THelpers, RawDocType>;
2412
2442
 
2413
2443
  /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */
2414
- projection(fields?: any | null): this;
2444
+ projection(): ProjectionFields<DocType> | null;
2445
+ projection(fields: null): null;
2446
+ projection(fields?: ProjectionFields<DocType> | string): ProjectionFields<DocType>;
2415
2447
 
2416
2448
  /** Determines the MongoDB nodes from which to read. */
2417
2449
  read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
@@ -3261,9 +3293,15 @@ declare module 'mongoose' {
3261
3293
  /** String representation of what type this is, like 'ObjectID' or 'Number' */
3262
3294
  instance: string;
3263
3295
 
3296
+ /** True if this SchemaType has a required validator. False otherwise. */
3297
+ isRequired?: boolean;
3298
+
3264
3299
  /** The options this SchemaType was instantiated with */
3265
3300
  options: AnyObject;
3266
3301
 
3302
+ /** The path to this SchemaType in a Schema. */
3303
+ path: string;
3304
+
3267
3305
  /**
3268
3306
  * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
3269
3307
  * looks at to determine the foreign collection it should query.
@@ -3297,11 +3335,19 @@ declare module 'mongoose' {
3297
3335
  /** Declares an unique index. */
3298
3336
  unique(bool: boolean): this;
3299
3337
 
3338
+ /** The validators that Mongoose should run to validate properties at this SchemaType's path. */
3339
+ validators: { message?: string; type?: string; validator?: Function }[];
3340
+
3300
3341
  /** Adds validator(s) for this document path. */
3301
3342
  validate(obj: RegExp | Function | any, errorMsg?: string,
3302
3343
  type?: string): this;
3303
3344
  }
3304
3345
 
3346
+ export interface SyncIndexesOptions extends mongodb.CreateIndexesOptions {
3347
+ continueOnError?: boolean
3348
+ }
3349
+ export type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
3350
+ type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
3305
3351
  type Callback<T = any> = (error: CallbackError, result: T) => void;
3306
3352
 
3307
3353
  type CallbackWithoutResult = (error: CallbackError) => void;
@@ -3332,6 +3378,12 @@ declare module 'mongoose' {
3332
3378
 
3333
3379
  constructor(type: string, value: any, path: string, reason?: NativeError, schemaType?: SchemaType);
3334
3380
  }
3381
+ export class SyncIndexesError extends Error {
3382
+ name: 'SyncIndexesError';
3383
+ errors?: Record<string, mongodb.MongoServerError>;
3384
+
3385
+ constructor(type: string, value: any, path: string, reason?: NativeError, schemaType?: SchemaType);
3386
+ }
3335
3387
 
3336
3388
  export class DisconnectedError extends Error {
3337
3389
  name: 'DisconnectedError';
package/lib/aggregate.js CHANGED
@@ -11,7 +11,6 @@ const getConstructorName = require('./helpers/getConstructorName');
11
11
  const prepareDiscriminatorPipeline = require('./helpers/aggregate/prepareDiscriminatorPipeline');
12
12
  const promiseOrCallback = require('./helpers/promiseOrCallback');
13
13
  const stringifyFunctionOperators = require('./helpers/aggregate/stringifyFunctionOperators');
14
- const util = require('util');
15
14
  const utils = require('./utils');
16
15
  const read = Query.prototype.read;
17
16
  const readConcern = Query.prototype.readConcern;
@@ -55,7 +54,7 @@ function Aggregate(pipeline, model) {
55
54
  this._model = model;
56
55
  this.options = {};
57
56
 
58
- if (arguments.length === 1 && util.isArray(pipeline)) {
57
+ if (arguments.length === 1 && Array.isArray(pipeline)) {
59
58
  this.append.apply(this, pipeline);
60
59
  }
61
60
  }
@@ -138,9 +137,9 @@ Aggregate.prototype.model = function(model) {
138
137
  */
139
138
 
140
139
  Aggregate.prototype.append = function() {
141
- const args = (arguments.length === 1 && util.isArray(arguments[0]))
140
+ const args = (arguments.length === 1 && Array.isArray(arguments[0]))
142
141
  ? arguments[0]
143
- : utils.args(arguments);
142
+ : [...arguments];
144
143
 
145
144
  if (!args.every(isOperator)) {
146
145
  throw new Error('Arguments must be aggregate pipeline operators');
@@ -176,7 +175,7 @@ Aggregate.prototype.append = function() {
176
175
  */
177
176
  Aggregate.prototype.addFields = function(arg) {
178
177
  const fields = {};
179
- if (typeof arg === 'object' && !util.isArray(arg)) {
178
+ if (typeof arg === 'object' && !Array.isArray(arg)) {
180
179
  Object.keys(arg).forEach(function(field) {
181
180
  fields[field] = arg[field];
182
181
  });
@@ -221,7 +220,7 @@ Aggregate.prototype.addFields = function(arg) {
221
220
  Aggregate.prototype.project = function(arg) {
222
221
  const fields = {};
223
222
 
224
- if (typeof arg === 'object' && !util.isArray(arg)) {
223
+ if (typeof arg === 'object' && !Array.isArray(arg)) {
225
224
  Object.keys(arg).forEach(function(field) {
226
225
  fields[field] = arg[field];
227
226
  });
@@ -372,7 +371,7 @@ Aggregate.prototype.near = function(arg) {
372
371
  */
373
372
 
374
373
  Aggregate.prototype.unwind = function() {
375
- const args = utils.args(arguments);
374
+ const args = [...arguments];
376
375
 
377
376
  const res = [];
378
377
  for (const arg of args) {
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  const ObjectId = require('../driver').get().ObjectId;
4
- const assert = require('assert');
5
4
 
6
5
  module.exports = function castObjectId(value) {
7
6
  if (value == null) {
@@ -25,5 +24,5 @@ module.exports = function castObjectId(value) {
25
24
  return new ObjectId(value.toString());
26
25
  }
27
26
 
28
- assert.ok(false);
27
+ return new ObjectId(value);
29
28
  };
package/lib/cast.js CHANGED
@@ -7,6 +7,7 @@
7
7
  const CastError = require('./error/cast');
8
8
  const StrictModeError = require('./error/strict');
9
9
  const Types = require('./schema/index');
10
+ const cast$expr = require('./helpers/query/cast$expr');
10
11
  const castTextSearch = require('./schema/operators/text');
11
12
  const get = require('./helpers/get');
12
13
  const getConstructorName = require('./helpers/getConstructorName');
@@ -36,14 +37,6 @@ module.exports = function cast(schema, obj, options, context) {
36
37
  return obj;
37
38
  }
38
39
 
39
- // bson 1.x has the unfortunate tendency to remove filters that have a top-level
40
- // `_bsontype` property. But we should still allow ObjectIds because
41
- // `Collection#find()` has a special case to support `find(objectid)`.
42
- // Should remove this when we upgrade to bson 4.x. See gh-8222, gh-8268
43
- if (obj.hasOwnProperty('_bsontype') && obj._bsontype !== 'ObjectID') {
44
- delete obj._bsontype;
45
- }
46
-
47
40
  if (schema != null && schema.discriminators != null && obj[schema.options.discriminatorKey] != null) {
48
41
  schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema;
49
42
  }
@@ -87,9 +80,7 @@ module.exports = function cast(schema, obj, options, context) {
87
80
 
88
81
  continue;
89
82
  } else if (path === '$expr') {
90
- if (typeof val !== 'object' || val == null) {
91
- throw new Error('`$expr` must be an object');
92
- }
83
+ val = cast$expr(val, schema);
93
84
  continue;
94
85
  } else if (path === '$elemMatch') {
95
86
  val = cast(schema, val, options, context);
@@ -153,7 +144,13 @@ module.exports = function cast(schema, obj, options, context) {
153
144
  remainingConds = {};
154
145
  pathLastHalf = split.slice(j).join('.');
155
146
  remainingConds[pathLastHalf] = val;
156
- obj[path] = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf];
147
+
148
+ const ret = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf];
149
+ if (ret === void 0) {
150
+ delete obj[path];
151
+ } else {
152
+ obj[path] = ret;
153
+ }
157
154
  } else {
158
155
  obj[path] = val;
159
156
  }
@@ -259,16 +256,24 @@ module.exports = function cast(schema, obj, options, context) {
259
256
  if (schema.nested[path]) {
260
257
  continue;
261
258
  }
262
- if (options.upsert && options.strict) {
263
- if (options.strict === 'throw') {
259
+
260
+ const strict = 'strict' in options ? options.strict : schema.options.strict;
261
+ const strictQuery = 'strictQuery' in options ?
262
+ options.strictQuery :
263
+ 'strict' in options ?
264
+ options.strict :
265
+ 'strict' in schema._userProvidedOptions ? schema._userProvidedOptions.strict :
266
+ schema.options.strictQuery;
267
+ if (options.upsert && strict) {
268
+ if (strict === 'throw') {
264
269
  throw new StrictModeError(path);
265
270
  }
266
271
  throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
267
272
  'schema, strict mode is `true`, and upsert is `true`.');
268
- } if (options.strictQuery === 'throw') {
273
+ } if (strictQuery === 'throw') {
269
274
  throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
270
275
  'schema and strictQuery is \'throw\'.');
271
- } else if (options.strictQuery) {
276
+ } else if (strictQuery) {
272
277
  delete obj[path];
273
278
  }
274
279
  } else if (val == null) {
package/lib/connection.js CHANGED
@@ -10,6 +10,7 @@ const Schema = require('./schema');
10
10
  const Collection = require('./driver').get().Collection;
11
11
  const STATES = require('./connectionstate');
12
12
  const MongooseError = require('./error/index');
13
+ const SyncIndexesError = require('./error/syncIndexes');
13
14
  const PromiseProvider = require('./promise_provider');
14
15
  const ServerSelectionError = require('./error/serverSelection');
15
16
  const applyPlugins = require('./helpers/schema/applyPlugins');
@@ -504,6 +505,10 @@ Connection.prototype.transaction = function transaction(fn, options) {
504
505
  }
505
506
  delete session[sessionNewDocuments];
506
507
  throw err;
508
+ })
509
+ .finally(() => {
510
+ session.endSession()
511
+ .catch(() => {});
507
512
  });
508
513
  });
509
514
  };
@@ -1376,11 +1381,40 @@ Connection.prototype.setClient = function setClient(client) {
1376
1381
  return this;
1377
1382
  };
1378
1383
 
1379
- Connection.prototype.syncIndexes = async function syncIndexes() {
1384
+ /**
1385
+ *
1386
+ * Syncs all the indexes for the models registered with this connection.
1387
+ *
1388
+ * @param {Object} options
1389
+ * @param {Boolean} options.continueOnError `false` by default. If set to `true`, mongoose will not throw an error if one model syncing failed, and will return an object where the keys are the names of the models, and the values are the results/errors for each model.
1390
+ * @returns
1391
+ */
1392
+ Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
1380
1393
  const result = {};
1381
- for (const model in this.models) {
1382
- result[model] = await this.model(model).syncIndexes();
1394
+ const errorsMap = { };
1395
+
1396
+ const { continueOnError } = options;
1397
+ delete options.continueOnError;
1398
+
1399
+ for (const model of Object.values(this.models)) {
1400
+ try {
1401
+ result[model.modelName] = await model.syncIndexes(options);
1402
+ } catch (err) {
1403
+ if (!continueOnError) {
1404
+ errorsMap[model.modelName] = err;
1405
+ break;
1406
+ } else {
1407
+ result[model.modelName] = err;
1408
+ }
1409
+ }
1383
1410
  }
1411
+
1412
+ if (!continueOnError && Object.keys(errorsMap).length) {
1413
+ const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(', ');
1414
+ const syncIndexesError = new SyncIndexesError(message, errorsMap);
1415
+ throw syncIndexesError;
1416
+ }
1417
+
1384
1418
  return result;
1385
1419
  };
1386
1420
 
package/lib/document.js CHANGED
@@ -885,7 +885,7 @@ function init(self, obj, doc, opts, prefix) {
885
885
  */
886
886
 
887
887
  Document.prototype.update = function update() {
888
- const args = utils.args(arguments);
888
+ const args = [...arguments];
889
889
  args.unshift({ _id: this._id });
890
890
  const query = this.constructor.update.apply(this.constructor, args);
891
891
 
@@ -962,7 +962,7 @@ Document.prototype.updateOne = function updateOne(doc, options, callback) {
962
962
  */
963
963
 
964
964
  Document.prototype.replaceOne = function replaceOne() {
965
- const args = utils.args(arguments);
965
+ const args = [...arguments];
966
966
  args.unshift({ _id: this._id });
967
967
  return this.constructor.replaceOne.apply(this.constructor, args);
968
968
  };
@@ -3801,7 +3801,7 @@ function applyVirtuals(self, json, options, toObjectOptions) {
3801
3801
  if (!path.startsWith(options.path + '.')) {
3802
3802
  continue;
3803
3803
  }
3804
- assignPath = path.substr(options.path.length + 1);
3804
+ assignPath = path.substring(options.path.length + 1);
3805
3805
  }
3806
3806
  const parts = assignPath.split('.');
3807
3807
  v = clone(self.get(path), options);
@@ -4136,7 +4136,7 @@ Document.prototype.equals = function(doc) {
4136
4136
 
4137
4137
  Document.prototype.populate = function populate() {
4138
4138
  const pop = {};
4139
- const args = utils.args(arguments);
4139
+ const args = [...arguments];
4140
4140
  let fn;
4141
4141
 
4142
4142
  if (args.length > 0) {
@@ -10,7 +10,6 @@ const Collection = require('mongodb').Collection;
10
10
  const ObjectId = require('./objectid');
11
11
  const get = require('../../helpers/get');
12
12
  const getConstructorName = require('../../helpers/getConstructorName');
13
- const sliced = require('sliced');
14
13
  const stream = require('stream');
15
14
  const util = require('util');
16
15
 
@@ -173,7 +172,7 @@ function iter(i) {
173
172
  if (debug) {
174
173
  if (typeof debug === 'function') {
175
174
  debug.apply(_this,
176
- [_this.name, i].concat(sliced(args, 0, args.length - 1)));
175
+ [_this.name, i].concat(args.slice(0, args.length - 1)));
177
176
  } else if (debug instanceof stream.Writable) {
178
177
  this.$printToStream(_this.name, i, args, debug);
179
178
  } else {
@@ -181,6 +181,17 @@ MongooseError.OverwriteModelError = require('./overwriteModel');
181
181
 
182
182
  MongooseError.MissingSchemaError = require('./missingSchema');
183
183
 
184
+ /**
185
+ * Thrown when the MongoDB Node driver can't connect to a valid server
186
+ * to send an operation to.
187
+ *
188
+ * @api public
189
+ * @memberOf Error
190
+ * @static MongooseServerSelectionError
191
+ */
192
+
193
+ MongooseError.MongooseServerSelectionError = require('./serverSelection');
194
+
184
195
  /**
185
196
  * An instance of this error will be returned if you used an array projection
186
197
  * and then modified the array in an unsafe way.
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies.
5
+ */
6
+
7
+ const MongooseError = require('./mongooseError');
8
+
9
+ /**
10
+ * SyncIndexes Error constructor.
11
+ *
12
+ * @param {String} message
13
+ * @param {String} errorsMap
14
+ * @inherits MongooseError
15
+ * @api private
16
+ */
17
+
18
+ class SyncIndexesError extends MongooseError {
19
+ constructor(message, errorsMap) {
20
+ super(message);
21
+ this.errors = errorsMap;
22
+ }
23
+ }
24
+
25
+ Object.defineProperty(SyncIndexesError.prototype, 'name', {
26
+ value: 'SyncIndexesError'
27
+ });
28
+
29
+
30
+ module.exports = SyncIndexesError;