DEV Community

Cover image for Mastering Schema and Model Definition in TypeScript: A Beginner's Guide
Qamar Khan
Qamar Khan

Posted on

Mastering Schema and Model Definition in TypeScript: A Beginner's Guide

Defining a Schema and Model in TypeScript (with Example)

When working with TypeScript and MongoDB (using Mongoose), defining schemas and models involves leveraging TypeScript interfaces and Mongoose schema definitions. Here’s a step-by-step guide with an example:

  • Install Required Packages

Ensure you have Mongoose and TypeScript installed in your project:

npm install mongoose npm install --save-dev @types/mongoose

  • Define a TypeScript Interface

The interface describes the structure of your documents.

types/User.ts

export interface IUser { name: string; email: string; age: number; }

  • Create a Mongoose Schema

Use the interface to help guide your schema design.

models/User.ts
import { Schema, model } from "mongoose";
import { IUser } from "../types/User";

const UserSchema = new Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: { type: Number, required: true }, });

export const UserModel = model("User", UserSchema);

  • Use the Model in Your Code

Now, you can use the UserModel to interact with the database.

index.ts import mongoose from "mongoose";
import { UserModel } from "./models/User";

async function main() {

// Connect to MongoDB await mongoose.connect("mongodb://localhost:27017/mydb");

// Create a new user
const newUser = new UserModel({ name: "Alice", email: "alice@example.com", age: 25, });

// Save the user to the database await newUser.save(); console.log("User saved:", newUser);

// Find all users
const users = await UserModel.find(); console.log("All Users:", users);

// Close the connection
await mongoose.disconnect(); } main().catch((err) => console.error(err));

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay