Home > Web Front-end > JS Tutorial > Mastering Schema and Model Definition in TypeScript: A Beginner&#s Guide

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

Barbara Streisand
Release: 2024-12-14 19:19:12
Original
805 people have browsed it

Mastering Schema and Model Definition in TypeScript: A Beginner

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));

The above is the detailed content of Mastering Schema and Model Definition in TypeScript: A Beginner&#s Guide. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template