mongooat v2.2.18
Mongooat
Mongooat is a TypeScript utility that combines Zod schemas with MongoDB, providing a straightforward method for model validation and type inference.
Installation
Install mongooat
using npm:
npm install mongooat
Usage
Import Mongooat
To get started, import the Mongooat
and Zod
from mongooat
:
import { Mongooat, z } from "mongooat";
Connecting to MongoDB
Create a new Mongooat
instance and connect to your MongoDB
database:
const mongooat = new Mongooat("mongodb://localhost:27017");
Switching Databases
Switch between databases using the useDb
method:
mongooat.useDb("mydb");
Defining a Model
Define a model using a Zod
schema:
const UserModel = mongooat.Model(
"users",
z.object({
name: z.string(),
age: z.number().optional(),
})
);
Performing Database Operations
With the defined model, you can now perform operations like finding documents:
const users = await UserModel.find();
You can use other operations like findById()
, insertOne()
, deleteOne()
, etc.
const user = await UserModel.findById("userId");
Type Inference
Extract TypeScript type by inferring the type of any model with Mongooat.infer<typeof Model>
.
type modelType = Mongooat.infer<typeof UserModel>;
// type ts = { name: string; age?: number | undefined; }
Accessing Dot-Notation Paths
Extract type-safe paths for nested properties in your schema using Mongooat.paths<typeof Model>
:
type modelPaths = Mongooat.paths<typeof UserModel>;
// type modelPaths = ("name" | "age")[]
For arrays, the key path will include the array index. If you use <idx>
as the index key, it will refer to every element in the array.
Note: This is not yet support nested maps, sets, and records (e.g. Map<string, {test: string}>
).
Contact
Acknowledgments
Credits to:
License
This project is licensed under the MIT License. See the LICENSE file for details.
9 months ago
9 months ago
11 months ago
11 months ago
11 months ago
10 months ago
10 months ago
9 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
11 months ago
11 months ago
12 months ago
1 year ago
1 year ago
1 year ago
1 year ago