MongoDB is a popular NoSQL database that is commonly used in modern web applications. It offers a flexible and scalable data storage solution that is ideal for projects of all sizes. TypeScript is a typed superset of JavaScript that adds type safety and other features to the language. In this tutorial, we will show you how to create models in MongoDB with TypeScript.


Prerequisites

Before we begin, make sure you have the following installed on your system:

  • Node.js
  • npm (Node Package Manager)
  • MongoDB

You should also have a basic understanding of TypeScript and MongoDB.


Setting up the project

First, create a new directory for your project and navigate to it in your terminal. Then, run the following command to initialize a new Node.js project:

npm init -y

This will create a package.json file in your directory.

Next, install the following dependencies:

npm install mongoose @types/mongoose

  • mongoose is the MongoDB object modeling tool that we will be using to create our models.
  • @types/mongoose contains TypeScript typings for Mongoose.


Creating the model

To create a model in MongoDB with TypeScript, we will define a TypeScript class that extends the mongoose.Document interface. This interface defines the methods and properties that our model will have.

Create a new file called user.model.ts in your project directory and add the following code:

import mongoose, { Document } from 'mongoose';

interface IUser extends Document {
  name: string;
  email: string;
  password: string;
}

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
});

const User = mongoose.model<IUser>('User', UserSchema);

export default User;

In this code, we define an interface IUser that extends mongoose.Document and specifies the properties that our model will have. We then create a UserSchema using mongoose.Schema, which defines the structure of the data that will be stored in the database. Finally, we create a User model using mongoose.model, passing in the name of the model and the UserSchema.


Connecting to the database

Before we can use our model, we need to connect to the database. Create a new file called database.ts in your project directory and add the following code:

import mongoose from 'mongoose';

async function connect() {
  try {
    await mongoose.connect('mongodb://localhost:27017/myapp', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('Connected to database');
  } catch (err) {
    console.error(err);
  }
}

export default connect;

In this code, we define an async function called connect that connects to the MongoDB database running on localhost:27017/myapp using mongoose.connect. We also specify some options for the connection, including useNewUrlParser and useUnifiedTopology. Finally, we log a message to the console if the connection is successful, or an error message if it fails.


Using the model

Now that we have created our model and connected to the database, we can start using it to interact with the data. Create a new file called app.ts in your project directory and add the following code:

import connect from './database';
import User from './user.model';

async function main() {
  await connect();

  const user = new User({
    name: 'John Doe',
    email: 'john.doe@example.com',
    password: 'secret',
  });

  await user.save();

  console.log('User saved:', user);
}

main().catch

In this code, we first import the connect function from database.ts and the User model from user.model.ts. We then define an async function called main that connects to the database using connect, creates a new User object with some sample data, and saves it to the database using the save method.

Finally, we log a message to the console indicating that the user has been saved.


Running the application

To run the application, execute the following command in your terminal:

npm run start

This will run the main function defined in app.ts. If everything is set up correctly, you should see a message in the console indicating that the user has been saved.


Conclusion

In this tutorial, we have shown you how to create models in MongoDB with TypeScript. We created a User model that extends the mongoose. Document interface, defined a connect function that connects to the database, and used the model to save a new user to the database. By following this example, you can create your own models and interact with MongoDB using TypeScript.