@zodmon/core 0.3.0 → 0.4.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/dist/index.cjs +210 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +381 -138
- package/dist/index.d.ts +381 -138
- package/dist/index.js +204 -16
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ObjectId,
|
|
2
|
-
import { ZodPipe, ZodCustom, ZodTransform, z } from 'zod';
|
|
1
|
+
import { ObjectId, Collection, MongoClientOptions } from 'mongodb';
|
|
2
|
+
import { ZodPipe, ZodCustom, ZodTransform, z, ZodDefault } from 'zod';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Options controlling how a field-level MongoDB index is created.
|
|
@@ -225,10 +225,12 @@ type CompoundIndexDefinition<TKeys extends string = string> = {
|
|
|
225
225
|
type FieldIndexDefinition = {
|
|
226
226
|
field: string;
|
|
227
227
|
} & IndexOptions;
|
|
228
|
+
/** Validation strategy for documents read from or written to MongoDB. */
|
|
229
|
+
type ValidationMode = 'strict' | 'strip' | 'passthrough';
|
|
228
230
|
/** Options passed to collection() as the third argument. */
|
|
229
231
|
type CollectionOptions<TKeys extends string = string> = {
|
|
230
232
|
indexes?: CompoundIndexDefinition<TKeys>[];
|
|
231
|
-
validation?:
|
|
233
|
+
validation?: ValidationMode;
|
|
232
234
|
warnUnindexedQueries?: boolean;
|
|
233
235
|
schemaVersion?: number;
|
|
234
236
|
migrate?: (doc: Record<string, unknown>, version: number) => Record<string, unknown>;
|
|
@@ -242,7 +244,7 @@ type CollectionOptions<TKeys extends string = string> = {
|
|
|
242
244
|
* This allows custom id types (nanoid, UUID, etc.) when needed.
|
|
243
245
|
*/
|
|
244
246
|
type ResolvedShape<TShape extends z.core.$ZodShape> = '_id' extends keyof TShape ? TShape : {
|
|
245
|
-
_id: ZodObjectId
|
|
247
|
+
_id: ZodDefault<ZodObjectId>;
|
|
246
248
|
} & TShape;
|
|
247
249
|
/**
|
|
248
250
|
* The document type inferred from a collection definition.
|
|
@@ -256,6 +258,23 @@ type ResolvedShape<TShape extends z.core.$ZodShape> = '_id' extends keyof TShape
|
|
|
256
258
|
type InferDocument<TDef extends {
|
|
257
259
|
readonly schema: z.ZodType;
|
|
258
260
|
}> = z.infer<TDef['schema']>;
|
|
261
|
+
/**
|
|
262
|
+
* The input type for inserting a document into a collection.
|
|
263
|
+
*
|
|
264
|
+
* Uses Zod's input type so fields with `.default()` (including the
|
|
265
|
+
* auto-generated `_id`) are optional. Custom `_id` fields without
|
|
266
|
+
* a default remain required.
|
|
267
|
+
*
|
|
268
|
+
* @example
|
|
269
|
+
* ```ts
|
|
270
|
+
* // Auto-generated _id — optional on insert
|
|
271
|
+
* type Insert = InferInsert<typeof Users>
|
|
272
|
+
* // { _id?: string | ObjectId; name: string; role?: string }
|
|
273
|
+
* ```
|
|
274
|
+
*/
|
|
275
|
+
type InferInsert<TDef extends {
|
|
276
|
+
readonly schema: z.ZodType;
|
|
277
|
+
}> = z.input<TDef['schema']>;
|
|
259
278
|
/**
|
|
260
279
|
* The immutable definition object returned by collection().
|
|
261
280
|
* Holds everything needed to later create a live collection handle.
|
|
@@ -271,6 +290,181 @@ type CollectionDefinition<TShape extends z.core.$ZodShape = z.core.$ZodShape> =
|
|
|
271
290
|
/** Erased collection type for use in generic contexts. */
|
|
272
291
|
type AnyCollection = CollectionDefinition<z.core.$ZodShape>;
|
|
273
292
|
|
|
293
|
+
/**
|
|
294
|
+
* Comparison operators for a field value of type `V`.
|
|
295
|
+
*
|
|
296
|
+
* Maps each MongoDB comparison operator to its expected value type.
|
|
297
|
+
* `$regex` is only available when `V` extends `string`.
|
|
298
|
+
*
|
|
299
|
+
* Used as the operator object that can be assigned to a field in {@link TypedFilter}.
|
|
300
|
+
*
|
|
301
|
+
* @example
|
|
302
|
+
* ```ts
|
|
303
|
+
* // As a raw object (without builder functions)
|
|
304
|
+
* const filter: TypedFilter<User> = { age: { $gt: 25, $lte: 65 } }
|
|
305
|
+
*
|
|
306
|
+
* // $regex only available on string fields
|
|
307
|
+
* const filter: TypedFilter<User> = { name: { $regex: /^A/i } }
|
|
308
|
+
* ```
|
|
309
|
+
*/
|
|
310
|
+
type ComparisonOperators<V> = {
|
|
311
|
+
/** Matches values equal to the specified value. */
|
|
312
|
+
$eq?: V;
|
|
313
|
+
/** Matches values not equal to the specified value. */
|
|
314
|
+
$ne?: V;
|
|
315
|
+
/** Matches values greater than the specified value. */
|
|
316
|
+
$gt?: V;
|
|
317
|
+
/** Matches values greater than or equal to the specified value. */
|
|
318
|
+
$gte?: V;
|
|
319
|
+
/** Matches values less than the specified value. */
|
|
320
|
+
$lt?: V;
|
|
321
|
+
/** Matches values less than or equal to the specified value. */
|
|
322
|
+
$lte?: V;
|
|
323
|
+
/** Matches any value in the specified array. */
|
|
324
|
+
$in?: V[];
|
|
325
|
+
/** Matches none of the values in the specified array. */
|
|
326
|
+
$nin?: V[];
|
|
327
|
+
/** Matches documents where the field exists (`true`) or does not exist (`false`). */
|
|
328
|
+
$exists?: boolean;
|
|
329
|
+
/** Negates a comparison operator. */
|
|
330
|
+
$not?: ComparisonOperators<V>;
|
|
331
|
+
} & (V extends string ? {
|
|
332
|
+
$regex?: RegExp | string;
|
|
333
|
+
} : unknown);
|
|
334
|
+
/** Depth counter for limiting dot-notation recursion. Index = current depth, value = next depth. */
|
|
335
|
+
type Prev = [never, 0, 1, 2];
|
|
336
|
+
/**
|
|
337
|
+
* Generates a union of all valid dot-separated paths for nested object fields in `T`.
|
|
338
|
+
*
|
|
339
|
+
* Recursion is limited to 3 levels deep to prevent TypeScript compilation performance issues.
|
|
340
|
+
* Only plain object fields are traversed — arrays, `Date`, `RegExp`, and `ObjectId` are
|
|
341
|
+
* treated as leaf nodes and do not produce sub-paths.
|
|
342
|
+
*
|
|
343
|
+
* @example
|
|
344
|
+
* ```ts
|
|
345
|
+
* type User = { address: { city: string; geo: { lat: number; lng: number } } }
|
|
346
|
+
*
|
|
347
|
+
* // DotPaths<User> = 'address.city' | 'address.geo' | 'address.geo.lat' | 'address.geo.lng'
|
|
348
|
+
* ```
|
|
349
|
+
*/
|
|
350
|
+
type DotPaths<T, Depth extends number = 3> = Depth extends 0 ? never : {
|
|
351
|
+
[K in keyof T & string]: NonNullable<T[K]> extends ReadonlyArray<unknown> | Date | RegExp | ObjectId ? never : NonNullable<T[K]> extends Record<string, unknown> ? `${K}.${keyof NonNullable<T[K]> & string}` | `${K}.${DotPaths<NonNullable<T[K]>, Prev[Depth]>}` : never;
|
|
352
|
+
}[keyof T & string];
|
|
353
|
+
/**
|
|
354
|
+
* Resolves the value type at a dot-separated path `P` within type `T`.
|
|
355
|
+
*
|
|
356
|
+
* Splits `P` on the first `.` and recursively descends into `T`'s nested types.
|
|
357
|
+
* Returns `never` if the path is invalid.
|
|
358
|
+
*
|
|
359
|
+
* @example
|
|
360
|
+
* ```ts
|
|
361
|
+
* type User = { address: { city: string; geo: { lat: number } } }
|
|
362
|
+
*
|
|
363
|
+
* // DotPathType<User, 'address.city'> = string
|
|
364
|
+
* // DotPathType<User, 'address.geo.lat'> = number
|
|
365
|
+
* ```
|
|
366
|
+
*/
|
|
367
|
+
type DotPathType<T, P extends string> = P extends `${infer K}.${infer Rest}` ? K extends keyof T ? Rest extends keyof NonNullable<T[K]> ? NonNullable<T[K]>[Rest] : DotPathType<NonNullable<T[K]>, Rest> : never : P extends keyof T ? T[P] : never;
|
|
368
|
+
/**
|
|
369
|
+
* Strict type-safe MongoDB filter query type.
|
|
370
|
+
*
|
|
371
|
+
* Validates filter objects at compile time — rejects nonexistent fields, type mismatches,
|
|
372
|
+
* and invalid operator usage. Unlike the MongoDB driver's `Filter<T>`, does NOT allow
|
|
373
|
+
* arbitrary keys via `& Document`.
|
|
374
|
+
*
|
|
375
|
+
* Supports three forms of filter expressions:
|
|
376
|
+
* - **Direct field values** (implicit `$eq`): `{ name: 'Alice' }`
|
|
377
|
+
* - **Comparison operators**: `{ age: { $gt: 25 } }` or `{ age: $gt(25) }`
|
|
378
|
+
* - **Dot notation** for nested fields up to 3 levels: `{ 'address.city': 'NYC' }`
|
|
379
|
+
*
|
|
380
|
+
* Logical operators `$and`, `$or`, and `$nor` accept arrays of `TypedFilter<T>`
|
|
381
|
+
* for composing complex queries.
|
|
382
|
+
*
|
|
383
|
+
* @example
|
|
384
|
+
* ```ts
|
|
385
|
+
* // Simple equality
|
|
386
|
+
* const filter: TypedFilter<User> = { name: 'Alice' }
|
|
387
|
+
*
|
|
388
|
+
* // Builder functions mixed with object literals
|
|
389
|
+
* const filter: TypedFilter<User> = { age: $gte(18), role: $in(['admin', 'mod']) }
|
|
390
|
+
*
|
|
391
|
+
* // Logical composition
|
|
392
|
+
* const filter = $and<User>(
|
|
393
|
+
* $or<User>({ role: 'admin' }, { role: 'moderator' }),
|
|
394
|
+
* { age: $gte(18) },
|
|
395
|
+
* { email: $exists() },
|
|
396
|
+
* )
|
|
397
|
+
*
|
|
398
|
+
* // Dynamic conditional building
|
|
399
|
+
* const conditions: TypedFilter<User>[] = []
|
|
400
|
+
* if (name) conditions.push({ name })
|
|
401
|
+
* if (minAge) conditions.push({ age: $gte(minAge) })
|
|
402
|
+
* const filter = conditions.length ? $and<User>(...conditions) : {}
|
|
403
|
+
* ```
|
|
404
|
+
*/
|
|
405
|
+
type TypedFilter<T> = {
|
|
406
|
+
[K in keyof T]?: T[K] | ComparisonOperators<T[K]>;
|
|
407
|
+
} & {
|
|
408
|
+
[P in DotPaths<T>]?: DotPathType<T, P> | ComparisonOperators<DotPathType<T, P>>;
|
|
409
|
+
} & {
|
|
410
|
+
/** Joins clauses with a logical AND. Matches documents that satisfy all filters. */
|
|
411
|
+
$and?: TypedFilter<T>[];
|
|
412
|
+
/** Joins clauses with a logical OR. Matches documents that satisfy at least one filter. */
|
|
413
|
+
$or?: TypedFilter<T>[];
|
|
414
|
+
/** Joins clauses with a logical NOR. Matches documents that fail all filters. */
|
|
415
|
+
$nor?: TypedFilter<T>[];
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Options for {@link findOne} and {@link findOneOrThrow}.
|
|
420
|
+
*/
|
|
421
|
+
type FindOneOptions = {
|
|
422
|
+
/** MongoDB projection — include (`1`) or exclude (`0`) fields. Typed projections deferred to v1.0. */
|
|
423
|
+
project?: Record<string, 0 | 1>;
|
|
424
|
+
/** Override the collection-level validation mode, or `false` to skip validation entirely. */
|
|
425
|
+
validate?: ValidationMode | false;
|
|
426
|
+
};
|
|
427
|
+
/**
|
|
428
|
+
* Find a single document matching the filter.
|
|
429
|
+
*
|
|
430
|
+
* Queries MongoDB, then validates the fetched document against the collection's
|
|
431
|
+
* Zod schema. Validation mode is resolved from the per-query option, falling
|
|
432
|
+
* back to the collection-level default (which defaults to `'strict'`).
|
|
433
|
+
*
|
|
434
|
+
* @param handle - The collection handle to query.
|
|
435
|
+
* @param filter - Type-safe filter to match documents.
|
|
436
|
+
* @param options - Optional projection and validation overrides.
|
|
437
|
+
* @returns The matched document, or `null` if no document matches.
|
|
438
|
+
* @throws {ZodmonValidationError} When the fetched document fails schema validation in strict mode.
|
|
439
|
+
*
|
|
440
|
+
* @example
|
|
441
|
+
* ```ts
|
|
442
|
+
* const user = await findOne(users, { name: 'Ada' })
|
|
443
|
+
* if (user) console.log(user.role) // typed as 'admin' | 'user'
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
declare function findOne<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOneOptions): Promise<InferDocument<TDef> | null>;
|
|
447
|
+
/**
|
|
448
|
+
* Find a single document matching the filter, or throw if none exists.
|
|
449
|
+
*
|
|
450
|
+
* Behaves identically to {@link findOne} but throws {@link ZodmonNotFoundError}
|
|
451
|
+
* instead of returning `null` when no document matches the filter.
|
|
452
|
+
*
|
|
453
|
+
* @param handle - The collection handle to query.
|
|
454
|
+
* @param filter - Type-safe filter to match documents.
|
|
455
|
+
* @param options - Optional projection and validation overrides.
|
|
456
|
+
* @returns The matched document (never null).
|
|
457
|
+
* @throws {ZodmonNotFoundError} When no document matches the filter.
|
|
458
|
+
* @throws {ZodmonValidationError} When the fetched document fails schema validation in strict mode.
|
|
459
|
+
*
|
|
460
|
+
* @example
|
|
461
|
+
* ```ts
|
|
462
|
+
* const user = await findOneOrThrow(users, { name: 'Ada' })
|
|
463
|
+
* console.log(user.role) // typed as 'admin' | 'user', guaranteed non-null
|
|
464
|
+
* ```
|
|
465
|
+
*/
|
|
466
|
+
declare function findOneOrThrow<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, filter: TypedFilter<InferDocument<TDef>>, options?: FindOneOptions): Promise<InferDocument<TDef>>;
|
|
467
|
+
|
|
274
468
|
/**
|
|
275
469
|
* Typed wrapper around a MongoDB driver `Collection`.
|
|
276
470
|
*
|
|
@@ -278,18 +472,95 @@ type AnyCollection = CollectionDefinition<z.core.$ZodShape>;
|
|
|
278
472
|
* (for runtime schema validation and index metadata) alongside the native
|
|
279
473
|
* driver collection parameterized with the inferred document type.
|
|
280
474
|
*
|
|
281
|
-
*
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
* @typeParam TDoc - The document type inferred from the Zod schema
|
|
285
|
-
* (e.g. `{ _id: ObjectId; name: string }`). Defaults to `Document`.
|
|
475
|
+
* @typeParam TDef - The collection definition type. Used to derive both
|
|
476
|
+
* the document type (`InferDocument`) and the insert type (`InferInsert`).
|
|
286
477
|
*/
|
|
287
|
-
declare class CollectionHandle<
|
|
478
|
+
declare class CollectionHandle<TDef extends AnyCollection = AnyCollection> {
|
|
288
479
|
/** The collection definition containing schema, name, and index metadata. */
|
|
289
|
-
readonly definition:
|
|
290
|
-
/** The underlying MongoDB driver collection, typed to
|
|
291
|
-
readonly native: Collection<
|
|
292
|
-
constructor(definition:
|
|
480
|
+
readonly definition: TDef;
|
|
481
|
+
/** The underlying MongoDB driver collection, typed to the inferred document type. */
|
|
482
|
+
readonly native: Collection<InferDocument<TDef>>;
|
|
483
|
+
constructor(definition: TDef, native: Collection<InferDocument<TDef>>);
|
|
484
|
+
/**
|
|
485
|
+
* Insert a single document into the collection.
|
|
486
|
+
*
|
|
487
|
+
* Validates the input against the collection's Zod schema before writing.
|
|
488
|
+
* Schema defaults (including auto-generated `_id`) are applied during
|
|
489
|
+
* validation. Returns the full document with all defaults filled in.
|
|
490
|
+
*
|
|
491
|
+
* @param doc - The document to insert. Fields with `.default()` are optional.
|
|
492
|
+
* @returns The inserted document with `_id` and all defaults applied.
|
|
493
|
+
* @throws {ZodmonValidationError} When the document fails schema validation.
|
|
494
|
+
*
|
|
495
|
+
* @example
|
|
496
|
+
* ```ts
|
|
497
|
+
* const users = db.use(Users)
|
|
498
|
+
* const user = await users.insertOne({ name: 'Ada' })
|
|
499
|
+
* console.log(user._id) // ObjectId (auto-generated)
|
|
500
|
+
* console.log(user.role) // 'user' (schema default)
|
|
501
|
+
* ```
|
|
502
|
+
*/
|
|
503
|
+
insertOne(doc: InferInsert<TDef>): Promise<InferDocument<TDef>>;
|
|
504
|
+
/**
|
|
505
|
+
* Insert multiple documents into the collection.
|
|
506
|
+
*
|
|
507
|
+
* Validates every document against the collection's Zod schema before
|
|
508
|
+
* writing any to MongoDB. If any document fails validation, none are
|
|
509
|
+
* inserted (fail-fast before the driver call).
|
|
510
|
+
*
|
|
511
|
+
* @param docs - The documents to insert.
|
|
512
|
+
* @returns The inserted documents with `_id` and all defaults applied.
|
|
513
|
+
* @throws {ZodmonValidationError} When any document fails schema validation.
|
|
514
|
+
*
|
|
515
|
+
* @example
|
|
516
|
+
* ```ts
|
|
517
|
+
* const created = await users.insertMany([
|
|
518
|
+
* { name: 'Ada' },
|
|
519
|
+
* { name: 'Bob', role: 'admin' },
|
|
520
|
+
* ])
|
|
521
|
+
* ```
|
|
522
|
+
*/
|
|
523
|
+
insertMany(docs: InferInsert<TDef>[]): Promise<InferDocument<TDef>[]>;
|
|
524
|
+
/**
|
|
525
|
+
* Find a single document matching the filter.
|
|
526
|
+
*
|
|
527
|
+
* Queries MongoDB, then validates the fetched document against the collection's
|
|
528
|
+
* Zod schema. Validation mode is resolved from the per-query option, falling
|
|
529
|
+
* back to the collection-level default (which defaults to `'strict'`).
|
|
530
|
+
*
|
|
531
|
+
* @param filter - Type-safe filter to match documents.
|
|
532
|
+
* @param options - Optional projection and validation overrides.
|
|
533
|
+
* @returns The matched document, or `null` if no document matches.
|
|
534
|
+
* @throws {ZodmonValidationError} When the fetched document fails schema validation in strict mode.
|
|
535
|
+
*
|
|
536
|
+
* @example
|
|
537
|
+
* ```ts
|
|
538
|
+
* const users = db.use(Users)
|
|
539
|
+
* const user = await users.findOne({ name: 'Ada' })
|
|
540
|
+
* if (user) console.log(user.role)
|
|
541
|
+
* ```
|
|
542
|
+
*/
|
|
543
|
+
findOne(filter: TypedFilter<InferDocument<TDef>>, options?: FindOneOptions): Promise<InferDocument<TDef> | null>;
|
|
544
|
+
/**
|
|
545
|
+
* Find a single document matching the filter, or throw if none exists.
|
|
546
|
+
*
|
|
547
|
+
* Behaves identically to {@link findOne} but throws {@link ZodmonNotFoundError}
|
|
548
|
+
* instead of returning `null` when no document matches the filter.
|
|
549
|
+
*
|
|
550
|
+
* @param filter - Type-safe filter to match documents.
|
|
551
|
+
* @param options - Optional projection and validation overrides.
|
|
552
|
+
* @returns The matched document (never null).
|
|
553
|
+
* @throws {ZodmonNotFoundError} When no document matches the filter.
|
|
554
|
+
* @throws {ZodmonValidationError} When the fetched document fails schema validation in strict mode.
|
|
555
|
+
*
|
|
556
|
+
* @example
|
|
557
|
+
* ```ts
|
|
558
|
+
* const users = db.use(Users)
|
|
559
|
+
* const user = await users.findOneOrThrow({ name: 'Ada' })
|
|
560
|
+
* console.log(user.role) // guaranteed non-null
|
|
561
|
+
* ```
|
|
562
|
+
*/
|
|
563
|
+
findOneOrThrow(filter: TypedFilter<InferDocument<TDef>>, options?: FindOneOptions): Promise<InferDocument<TDef>>;
|
|
293
564
|
}
|
|
294
565
|
|
|
295
566
|
/**
|
|
@@ -324,7 +595,7 @@ declare class Database {
|
|
|
324
595
|
* @param def - A collection definition created by `collection()`.
|
|
325
596
|
* @returns A typed collection handle for CRUD operations.
|
|
326
597
|
*/
|
|
327
|
-
use<TShape extends z.core.$ZodShape>(def: CollectionDefinition<TShape>): CollectionHandle<
|
|
598
|
+
use<TShape extends z.core.$ZodShape>(def: CollectionDefinition<TShape>): CollectionHandle<CollectionDefinition<TShape>>;
|
|
328
599
|
/**
|
|
329
600
|
* Synchronize indexes defined in registered collections with MongoDB.
|
|
330
601
|
*
|
|
@@ -461,173 +732,145 @@ declare class IndexBuilder<TKeys extends string> {
|
|
|
461
732
|
declare function index<TKeys extends string>(fields: Record<TKeys, IndexDirection>): IndexBuilder<TKeys>;
|
|
462
733
|
|
|
463
734
|
/**
|
|
464
|
-
*
|
|
735
|
+
* Insert a single document into the collection.
|
|
465
736
|
*
|
|
466
|
-
*
|
|
467
|
-
*
|
|
468
|
-
*
|
|
469
|
-
* - Called with an **existing `ObjectId`**: returns it unchanged.
|
|
470
|
-
*
|
|
471
|
-
* This is a convenience wrapper that removes the need for `new ObjectId()`
|
|
472
|
-
* boilerplate throughout application code.
|
|
737
|
+
* Validates the input against the collection's Zod schema before writing.
|
|
738
|
+
* Schema defaults (including auto-generated `_id`) are applied during
|
|
739
|
+
* validation. Returns the full document with all defaults filled in.
|
|
473
740
|
*
|
|
474
|
-
* @param
|
|
475
|
-
*
|
|
476
|
-
* @returns
|
|
741
|
+
* @param handle - The collection handle to insert into.
|
|
742
|
+
* @param doc - The document to insert. Fields with `.default()` are optional.
|
|
743
|
+
* @returns The inserted document with `_id` and all defaults applied.
|
|
744
|
+
* @throws {ZodmonValidationError} When the document fails schema validation.
|
|
477
745
|
*
|
|
478
746
|
* @example
|
|
479
747
|
* ```ts
|
|
480
|
-
*
|
|
481
|
-
*
|
|
482
|
-
*
|
|
748
|
+
* const user = await insertOne(users, { name: 'Ada' })
|
|
749
|
+
* console.log(user._id) // ObjectId (auto-generated)
|
|
750
|
+
* console.log(user.role) // 'user' (schema default)
|
|
483
751
|
* ```
|
|
484
752
|
*/
|
|
485
|
-
declare function
|
|
486
|
-
declare function oid(value: string): ObjectId;
|
|
487
|
-
declare function oid(value: ObjectId): ObjectId;
|
|
753
|
+
declare function insertOne<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, doc: InferInsert<TDef>): Promise<InferDocument<TDef>>;
|
|
488
754
|
/**
|
|
489
|
-
*
|
|
755
|
+
* Insert multiple documents into the collection.
|
|
490
756
|
*
|
|
491
|
-
*
|
|
492
|
-
*
|
|
757
|
+
* Validates every document against the collection's Zod schema before
|
|
758
|
+
* writing any to MongoDB. If any document fails validation, none are
|
|
759
|
+
* inserted (fail-fast before the driver call).
|
|
493
760
|
*
|
|
494
|
-
* @param
|
|
495
|
-
* @
|
|
761
|
+
* @param handle - The collection handle to insert into.
|
|
762
|
+
* @param docs - The documents to insert.
|
|
763
|
+
* @returns The inserted documents with `_id` and all defaults applied.
|
|
764
|
+
* @throws {ZodmonValidationError} When any document fails schema validation.
|
|
496
765
|
*
|
|
497
766
|
* @example
|
|
498
767
|
* ```ts
|
|
499
|
-
* const
|
|
500
|
-
*
|
|
501
|
-
*
|
|
502
|
-
*
|
|
768
|
+
* const users = await insertMany(handle, [
|
|
769
|
+
* { name: 'Ada' },
|
|
770
|
+
* { name: 'Bob', role: 'admin' },
|
|
771
|
+
* ])
|
|
503
772
|
* ```
|
|
504
773
|
*/
|
|
505
|
-
declare function
|
|
774
|
+
declare function insertMany<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, docs: InferInsert<TDef>[]): Promise<InferDocument<TDef>[]>;
|
|
506
775
|
|
|
507
776
|
/**
|
|
508
|
-
*
|
|
777
|
+
* Thrown when a query expected to find a document returns no results.
|
|
509
778
|
*
|
|
510
|
-
*
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
* Used as the operator object that can be assigned to a field in {@link TypedFilter}.
|
|
779
|
+
* Used by {@link findOneOrThrow} when no document matches the provided filter.
|
|
780
|
+
* Callers can inspect `.collection` to identify which collection the query targeted.
|
|
514
781
|
*
|
|
515
782
|
* @example
|
|
516
783
|
* ```ts
|
|
517
|
-
*
|
|
518
|
-
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
521
|
-
*
|
|
784
|
+
* try {
|
|
785
|
+
* await users.findOneOrThrow({ name: 'nonexistent' })
|
|
786
|
+
* } catch (err) {
|
|
787
|
+
* if (err instanceof ZodmonNotFoundError) {
|
|
788
|
+
* console.log(err.message) // => 'Document not found in "users"'
|
|
789
|
+
* console.log(err.collection) // => 'users'
|
|
790
|
+
* }
|
|
791
|
+
* }
|
|
522
792
|
* ```
|
|
523
793
|
*/
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
/** Matches values greater than or equal to the specified value. */
|
|
532
|
-
$gte?: V;
|
|
533
|
-
/** Matches values less than the specified value. */
|
|
534
|
-
$lt?: V;
|
|
535
|
-
/** Matches values less than or equal to the specified value. */
|
|
536
|
-
$lte?: V;
|
|
537
|
-
/** Matches any value in the specified array. */
|
|
538
|
-
$in?: V[];
|
|
539
|
-
/** Matches none of the values in the specified array. */
|
|
540
|
-
$nin?: V[];
|
|
541
|
-
/** Matches documents where the field exists (`true`) or does not exist (`false`). */
|
|
542
|
-
$exists?: boolean;
|
|
543
|
-
/** Negates a comparison operator. */
|
|
544
|
-
$not?: ComparisonOperators<V>;
|
|
545
|
-
} & (V extends string ? {
|
|
546
|
-
$regex?: RegExp | string;
|
|
547
|
-
} : unknown);
|
|
548
|
-
/** Depth counter for limiting dot-notation recursion. Index = current depth, value = next depth. */
|
|
549
|
-
type Prev = [never, 0, 1, 2];
|
|
794
|
+
declare class ZodmonNotFoundError extends Error {
|
|
795
|
+
readonly name = "ZodmonNotFoundError";
|
|
796
|
+
/** The MongoDB collection name where the query found no results. */
|
|
797
|
+
readonly collection: string;
|
|
798
|
+
constructor(collection: string);
|
|
799
|
+
}
|
|
800
|
+
|
|
550
801
|
/**
|
|
551
|
-
*
|
|
802
|
+
* Thrown when a document fails Zod schema validation before a MongoDB write.
|
|
552
803
|
*
|
|
553
|
-
*
|
|
554
|
-
*
|
|
555
|
-
*
|
|
804
|
+
* Wraps the original `ZodError` with the collection name and a human-readable
|
|
805
|
+
* message listing each invalid field and its error. Callers can inspect
|
|
806
|
+
* `.zodError.issues` for programmatic access to individual failures.
|
|
556
807
|
*
|
|
557
808
|
* @example
|
|
558
809
|
* ```ts
|
|
559
|
-
*
|
|
560
|
-
*
|
|
561
|
-
*
|
|
810
|
+
* try {
|
|
811
|
+
* await users.insertOne({ name: 123 })
|
|
812
|
+
* } catch (err) {
|
|
813
|
+
* if (err instanceof ZodmonValidationError) {
|
|
814
|
+
* console.log(err.message)
|
|
815
|
+
* // => 'Validation failed for "users": name (Expected string, received number)'
|
|
816
|
+
* console.log(err.collection) // => 'users'
|
|
817
|
+
* console.log(err.zodError) // => ZodError with .issues array
|
|
818
|
+
* }
|
|
819
|
+
* }
|
|
562
820
|
* ```
|
|
563
821
|
*/
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
822
|
+
declare class ZodmonValidationError extends Error {
|
|
823
|
+
readonly name = "ZodmonValidationError";
|
|
824
|
+
/** The MongoDB collection name where the validation failed. */
|
|
825
|
+
readonly collection: string;
|
|
826
|
+
/** The original Zod validation error with detailed issue information. */
|
|
827
|
+
readonly zodError: z.ZodError;
|
|
828
|
+
constructor(collection: string, zodError: z.ZodError);
|
|
829
|
+
}
|
|
830
|
+
|
|
567
831
|
/**
|
|
568
|
-
*
|
|
832
|
+
* Create or coerce a MongoDB `ObjectId`.
|
|
569
833
|
*
|
|
570
|
-
*
|
|
571
|
-
*
|
|
834
|
+
* - Called with **no arguments**: generates a brand-new `ObjectId`.
|
|
835
|
+
* - Called with a **hex string**: coerces it to an `ObjectId` via
|
|
836
|
+
* `ObjectId.createFromHexString`.
|
|
837
|
+
* - Called with an **existing `ObjectId`**: returns it unchanged.
|
|
838
|
+
*
|
|
839
|
+
* This is a convenience wrapper that removes the need for `new ObjectId()`
|
|
840
|
+
* boilerplate throughout application code.
|
|
841
|
+
*
|
|
842
|
+
* @param value - Optional hex string or `ObjectId` to coerce. Omit to
|
|
843
|
+
* generate a new `ObjectId`.
|
|
844
|
+
* @returns An `ObjectId` instance.
|
|
572
845
|
*
|
|
573
846
|
* @example
|
|
574
847
|
* ```ts
|
|
575
|
-
*
|
|
576
|
-
*
|
|
577
|
-
* //
|
|
578
|
-
* // DotPathType<User, 'address.geo.lat'> = number
|
|
848
|
+
* oid() // new random ObjectId
|
|
849
|
+
* oid('64f1a2b3c4d5e6f7a8b9c0d1') // coerce hex string
|
|
850
|
+
* oid(existingId) // pass-through
|
|
579
851
|
* ```
|
|
580
852
|
*/
|
|
581
|
-
|
|
853
|
+
declare function oid(): ObjectId;
|
|
854
|
+
declare function oid(value: string): ObjectId;
|
|
855
|
+
declare function oid(value: ObjectId): ObjectId;
|
|
582
856
|
/**
|
|
583
|
-
*
|
|
584
|
-
*
|
|
585
|
-
* Validates filter objects at compile time — rejects nonexistent fields, type mismatches,
|
|
586
|
-
* and invalid operator usage. Unlike the MongoDB driver's `Filter<T>`, does NOT allow
|
|
587
|
-
* arbitrary keys via `& Document`.
|
|
857
|
+
* Type guard that narrows an `unknown` value to `ObjectId`.
|
|
588
858
|
*
|
|
589
|
-
*
|
|
590
|
-
*
|
|
591
|
-
* - **Comparison operators**: `{ age: { $gt: 25 } }` or `{ age: $gt(25) }`
|
|
592
|
-
* - **Dot notation** for nested fields up to 3 levels: `{ 'address.city': 'NYC' }`
|
|
859
|
+
* Uses `instanceof` internally, so it works with any value without risk
|
|
860
|
+
* of throwing.
|
|
593
861
|
*
|
|
594
|
-
*
|
|
595
|
-
*
|
|
862
|
+
* @param value - The value to check.
|
|
863
|
+
* @returns `true` if `value` is an `ObjectId` instance.
|
|
596
864
|
*
|
|
597
865
|
* @example
|
|
598
866
|
* ```ts
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
*
|
|
603
|
-
* const filter: TypedFilter<User> = { age: $gte(18), role: $in(['admin', 'mod']) }
|
|
604
|
-
*
|
|
605
|
-
* // Logical composition
|
|
606
|
-
* const filter = $and<User>(
|
|
607
|
-
* $or<User>({ role: 'admin' }, { role: 'moderator' }),
|
|
608
|
-
* { age: $gte(18) },
|
|
609
|
-
* { email: $exists() },
|
|
610
|
-
* )
|
|
611
|
-
*
|
|
612
|
-
* // Dynamic conditional building
|
|
613
|
-
* const conditions: TypedFilter<User>[] = []
|
|
614
|
-
* if (name) conditions.push({ name })
|
|
615
|
-
* if (minAge) conditions.push({ age: $gte(minAge) })
|
|
616
|
-
* const filter = conditions.length ? $and<User>(...conditions) : {}
|
|
867
|
+
* const raw: unknown = getFromDb()
|
|
868
|
+
* if (isOid(raw)) {
|
|
869
|
+
* console.log(raw.toHexString()) // raw is narrowed to ObjectId
|
|
870
|
+
* }
|
|
617
871
|
* ```
|
|
618
872
|
*/
|
|
619
|
-
|
|
620
|
-
[K in keyof T]?: T[K] | ComparisonOperators<T[K]>;
|
|
621
|
-
} & {
|
|
622
|
-
[P in DotPaths<T>]?: DotPathType<T, P> | ComparisonOperators<DotPathType<T, P>>;
|
|
623
|
-
} & {
|
|
624
|
-
/** Joins clauses with a logical AND. Matches documents that satisfy all filters. */
|
|
625
|
-
$and?: TypedFilter<T>[];
|
|
626
|
-
/** Joins clauses with a logical OR. Matches documents that satisfy at least one filter. */
|
|
627
|
-
$or?: TypedFilter<T>[];
|
|
628
|
-
/** Joins clauses with a logical NOR. Matches documents that fail all filters. */
|
|
629
|
-
$nor?: TypedFilter<T>[];
|
|
630
|
-
};
|
|
873
|
+
declare function isOid(value: unknown): value is ObjectId;
|
|
631
874
|
|
|
632
875
|
/**
|
|
633
876
|
* Matches values equal to the specified value.
|
|
@@ -901,4 +1144,4 @@ declare function getRefMetadata(schema: unknown): RefMetadata | undefined;
|
|
|
901
1144
|
*/
|
|
902
1145
|
declare function installRefExtension(): void;
|
|
903
1146
|
|
|
904
|
-
export { $and, $eq, $exists, $gt, $gte, $in, $lt, $lte, $ne, $nin, $nor, $not, $or, $regex, type AnyCollection, type CollectionDefinition, CollectionHandle, type CollectionOptions, type ComparisonOperators, type CompoundIndexDefinition, Database, type DotPathType, type DotPaths, type FieldIndexDefinition, IndexBuilder, type IndexMetadata, type IndexOptions, type InferDocument, type RefMarker, type RefMetadata, type ResolvedShape, type TypedFilter, type ZodObjectId, collection, createClient, extractDbName, extractFieldIndexes, getIndexMetadata, getRefMetadata, index, installExtensions, installRefExtension, isOid, objectId, oid, raw };
|
|
1147
|
+
export { $and, $eq, $exists, $gt, $gte, $in, $lt, $lte, $ne, $nin, $nor, $not, $or, $regex, type AnyCollection, type CollectionDefinition, CollectionHandle, type CollectionOptions, type ComparisonOperators, type CompoundIndexDefinition, Database, type DotPathType, type DotPaths, type FieldIndexDefinition, type FindOneOptions, IndexBuilder, type IndexMetadata, type IndexOptions, type InferDocument, type InferInsert, type RefMarker, type RefMetadata, type ResolvedShape, type TypedFilter, type ValidationMode, type ZodObjectId, ZodmonNotFoundError, ZodmonValidationError, collection, createClient, extractDbName, extractFieldIndexes, findOne, findOneOrThrow, getIndexMetadata, getRefMetadata, index, insertMany, insertOne, installExtensions, installRefExtension, isOid, objectId, oid, raw };
|