UNPKG

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