UNPKG

12.2 kBTypeScriptView Raw
1declare module 'mongoose' {
2 import mongodb = require('mongodb');
3
4 /** A list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. */
5 type pathsToSkip = string[] | string;
6
7 interface DocumentSetOptions {
8 merge?: boolean;
9
10 [key: string]: any;
11 }
12
13 class ModifiedPathsSnapshot {}
14
15 /**
16 * Generic types for Document:
17 * * T - the type of _id
18 * * TQueryHelpers - Object with any helpers that should be mixed into the Query type
19 * * DocType - the type of the actual Document created
20 */
21 class Document<T = unknown, TQueryHelpers = any, DocType = any> {
22 constructor(doc?: any);
23
24 /** This documents _id. */
25 _id?: T;
26
27 /** This documents __v. */
28 __v?: any;
29
30 /** Assert that a given path or paths is populated. Throws an error if not populated. */
31 $assertPopulated<Paths = {}>(path: string | string[], values?: Partial<Paths>): Omit<this, keyof Paths> & Paths;
32
33 /** Clear the document's modified paths. */
34 $clearModifiedPaths(): this;
35
36 /** Returns a deep clone of this document */
37 $clone(): this;
38
39 /**
40 * Creates a snapshot of this document's internal change tracking state. You can later
41 * reset this document's change tracking state using `$restoreModifiedPathsSnapshot()`.
42 */
43 $createModifiedPathsSnapshot(): ModifiedPathsSnapshot;
44
45 /* Get all subdocs (by bfs) */
46 $getAllSubdocs(): Document[];
47
48 /** Don't run validation on this path or persist changes to this path. */
49 $ignore(path: string): void;
50
51 /** Checks if a path is set to its default. */
52 $isDefault(path: string): boolean;
53
54 /** Getter/setter, determines whether the document was removed or not. */
55 $isDeleted(val?: boolean): boolean;
56
57 /** Returns an array of all populated documents associated with the query */
58 $getPopulatedDocs(): Document[];
59
60 /**
61 * Increments the numeric value at `path` by the given `val`.
62 * When you call `save()` on this document, Mongoose will send a
63 * `$inc` as opposed to a `$set`.
64 */
65 $inc(path: string | string[], val?: number): this;
66
67 /**
68 * Returns true if the given path is nullish or only contains empty objects.
69 * Useful for determining whether this subdoc will get stripped out by the
70 * [minimize option](/docs/guide.html#minimize).
71 */
72 $isEmpty(path: string): boolean;
73
74 /** Checks if a path is invalid */
75 $isValid(path: string): boolean;
76
77 /**
78 * Empty object that you can use for storing properties on the document. This
79 * is handy for passing data to middleware without conflicting with Mongoose
80 * internals.
81 */
82 $locals: Record<string, unknown>;
83
84 /** Marks a path as valid, removing existing validation errors. */
85 $markValid(path: string): void;
86
87 /** Returns the model with the given name on this document's associated connection. */
88 $model<ModelType = Model<unknown>>(name: string): ModelType;
89 $model<ModelType = Model<DocType>>(): ModelType;
90
91 /**
92 * A string containing the current operation that Mongoose is executing
93 * on this document. Can be `null`, `'save'`, `'validate'`, or `'remove'`.
94 */
95 $op: 'save' | 'validate' | 'remove' | null;
96
97 /**
98 * Restore this document's change tracking state to the given snapshot.
99 * Note that `$restoreModifiedPathsSnapshot()` does **not** modify the document's
100 * properties, just resets the change tracking state.
101 */
102 $restoreModifiedPathsSnapshot(snapshot: ModifiedPathsSnapshot): this;
103
104 /**
105 * Getter/setter around the session associated with this document. Used to
106 * automatically set `session` if you `save()` a doc that you got from a
107 * query with an associated session.
108 */
109 $session(session?: ClientSession | null): ClientSession | null;
110
111 /** Alias for `set()`, used internally to avoid conflicts */
112 $set(path: string | Record<string, any>, val: any, type: any, options?: DocumentSetOptions): this;
113 $set(path: string | Record<string, any>, val: any, options?: DocumentSetOptions): this;
114 $set(value: string | Record<string, any>): this;
115
116 /** Set this property to add additional query filters when Mongoose saves this document and `isNew` is false. */
117 $where: Record<string, unknown>;
118
119 /** If this is a discriminator model, `baseModelName` is the name of the base model. */
120 baseModelName?: string;
121
122 /** Collection the model uses. */
123 collection: Collection;
124
125 /** Connection the model uses. */
126 db: Connection;
127
128 /** Removes this document from the db. */
129 deleteOne(options?: QueryOptions): QueryWithHelpers<
130 mongodb.DeleteResult,
131 this,
132 TQueryHelpers,
133 DocType,
134 'deleteOne'
135 >;
136
137 /**
138 * Takes a populated field and returns it to its unpopulated state. If called with
139 * no arguments, then all populated fields are returned to their unpopulated state.
140 */
141 depopulate(path?: string | string[]): this;
142
143 /**
144 * Returns the list of paths that have been directly modified. A direct
145 * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`,
146 * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`.
147 */
148 directModifiedPaths(): Array<string>;
149
150 /**
151 * Returns true if this document is equal to another document.
152 *
153 * Documents are considered equal when they have matching `_id`s, unless neither
154 * document has an `_id`, in which case this function falls back to using
155 * `deepEqual()`.
156 */
157 equals(doc: Document<T>): boolean;
158
159 /** Returns the current validation errors. */
160 errors?: Error.ValidationError;
161
162 /** Returns the value of a path. */
163 get<T extends keyof DocType>(path: T, type?: any, options?: any): DocType[T];
164 get(path: string, type?: any, options?: any): any;
165
166 /**
167 * Returns the changes that happened to the document
168 * in the format that will be sent to MongoDB.
169 */
170 getChanges(): UpdateQuery<this>;
171
172 /** The string version of this documents _id. */
173 id?: any;
174
175 /** Signal that we desire an increment of this documents version. */
176 increment(): this;
177
178 /**
179 * Initializes the document without setters or marking anything modified.
180 * Called internally after a document is returned from mongodb. Normally,
181 * you do **not** need to call this function on your own.
182 */
183 init(obj: AnyObject, opts?: AnyObject): this;
184
185 /** Marks a path as invalid, causing validation to fail. */
186 invalidate<T extends keyof DocType>(path: T, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null;
187 invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null;
188
189 /** Returns true if `path` was directly set and modified, else false. */
190 isDirectModified<T extends keyof DocType>(path: T | Array<T>): boolean;
191 isDirectModified(path: string | Array<string>): boolean;
192
193 /** Checks if `path` was explicitly selected. If no projection, always returns true. */
194 isDirectSelected<T extends keyof DocType>(path: T): boolean;
195 isDirectSelected(path: string): boolean;
196
197 /** Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. */
198 isInit<T extends keyof DocType>(path: T): boolean;
199 isInit(path: string): boolean;
200
201 /**
202 * Returns true if any of the given paths are modified, else false. If no arguments, returns `true` if any path
203 * in this document is modified.
204 */
205 isModified<T extends keyof DocType>(path?: T | Array<T>, options?: { ignoreAtomics?: boolean } | null): boolean;
206 isModified(path?: string | Array<string>, options?: { ignoreAtomics?: boolean } | null): boolean;
207
208 /** Boolean flag specifying if the document is new. */
209 isNew: boolean;
210
211 /** Checks if `path` was selected in the source query which initialized this document. */
212 isSelected<T extends keyof DocType>(path: T): boolean;
213 isSelected(path: string): boolean;
214
215 /** Marks the path as having pending changes to write to the db. */
216 markModified<T extends keyof DocType>(path: T, scope?: any): void;
217 markModified(path: string, scope?: any): void;
218
219 /** Returns the model with the given name on this document's associated connection. */
220 model<ModelType = Model<unknown>>(name: string): ModelType;
221 model<ModelType = Model<DocType>>(): ModelType;
222
223 /** Returns the list of paths that have been modified. */
224 modifiedPaths(options?: { includeChildren?: boolean }): Array<string>;
225
226 /**
227 * Overwrite all values in this document with the values of `obj`, except
228 * for immutable properties. Behaves similarly to `set()`, except for it
229 * unsets all properties that aren't in `obj`.
230 */
231 overwrite(obj: AnyObject): this;
232
233 /**
234 * If this document is a subdocument or populated document, returns the
235 * document's parent. Returns undefined otherwise.
236 */
237 $parent(): Document | undefined;
238
239 /** Populates document references. */
240 populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<MergeType<this, Paths>>;
241 populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions): Promise<MergeType<this, Paths>>;
242
243 /** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */
244 populated(path: string): any;
245
246 /** Sends a replaceOne command with this document `_id` as the query selector. */
247 replaceOne(replacement?: AnyObject, options?: QueryOptions | null): Query<any, this>;
248
249 /** Saves this document by inserting a new document into the database if [document.isNew](/docs/api/document.html#document_Document-isNew) is `true`, or sends an [updateOne](/docs/api/document.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. */
250 save(options?: SaveOptions): Promise<this>;
251
252 /** The document's schema. */
253 schema: Schema;
254
255 /** Sets the value of a path, or many paths. */
256 set<T extends keyof DocType>(path: T, val: DocType[T], type: any, options?: DocumentSetOptions): this;
257 set(path: string | Record<string, any>, val: any, type: any, options?: DocumentSetOptions): this;
258 set(path: string | Record<string, any>, val: any, options?: DocumentSetOptions): this;
259 set(value: string | Record<string, any>): this;
260
261 /** The return value of this method is used in calls to JSON.stringify(doc). */
262 toJSON<T = Require_id<DocType>>(options?: ToObjectOptions & { flattenMaps?: true }): FlattenMaps<T>;
263 toJSON<T = Require_id<DocType>>(options: ToObjectOptions & { flattenMaps: false }): T;
264
265 /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
266 toObject<T = Require_id<DocType>>(options?: ToObjectOptions): Require_id<T>;
267
268 /** Clears the modified state on the specified path. */
269 unmarkModified<T extends keyof DocType>(path: T): void;
270 unmarkModified(path: string): void;
271
272 /** Sends an updateOne command with this document `_id` as the query selector. */
273 updateOne(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null): Query<any, this>;
274
275 /** Executes registered validation rules for this document. */
276 validate<T extends keyof DocType>(pathsToValidate?: T | T[], options?: AnyObject): Promise<void>;
277 validate(pathsToValidate?: pathsToValidate, options?: AnyObject): Promise<void>;
278 validate(options: { pathsToSkip?: pathsToSkip }): Promise<void>;
279
280 /** Executes registered validation rules (skipping asynchronous validators) for this document. */
281 validateSync(options: { pathsToSkip?: pathsToSkip, [k: string]: any }): Error.ValidationError | null;
282 validateSync<T extends keyof DocType>(pathsToValidate?: T | T[], options?: AnyObject): Error.ValidationError | null;
283 validateSync(pathsToValidate?: pathsToValidate, options?: AnyObject): Error.ValidationError | null;
284 }
285}