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)); 
              
    
Top comments (0)