TypeScript is a statically-typed language that is a superset of JavaScript. MongoDB, on the other hand, is a popular NoSQL database that stores data in a document-oriented manner. In this tutorial, we'll explore how to use TypeScript with MongoDB and build a simple CRUD (Create, Read, Update, Delete) application.
Prerequisites
To follow along with this tutorial, you should have basic knowledge of TypeScript, Node.js, and MongoDB.
Step 1: Set up a TypeScript project
First, we need to set up a TypeScript project. Create a new directory for your project and run the following command to initialize a new Node.js project:
npm init -yNext, install TypeScript as a development dependency:
npm install --save-dev typescriptCreate a new file named tsconfig.json in the root of your project directory and add the following configuration:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "dist",
"strict": true,
"esModuleInterop": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}This configuration sets the target version of ECMAScript to ES6, enables strict type-checking, and specifies an output directory for the compiled TypeScript code.
Step 2: Install dependencies
Next, we need to install the required dependencies for our project. Install the mongodb and @types/mongodb packages:
npm install mongodb @types/mongodbStep 3: Connect to MongoDB
In this step, we'll establish a connection to MongoDB. Create a new file named index.ts in the src directory and add the following code:
import { MongoClient } from 'mongodb';
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
MongoClient.connect(url, (err, client) => {
if (err) {
console.error(err);
return;
}
const db = client.db(dbName);
console.log(`Connected to MongoDB at ${url}`);
});
This code connects to a MongoDB instance running on the local machine and logs a message to the console if the connection is successful.
Step 4: Perform CRUD operations
In this step, we'll perform CRUD operations on our MongoDB database. Add the following code to the index.ts file:
import { MongoClient, ObjectId } from 'mongodb';
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
interface User {
_id: ObjectId;
name: string;
email: string;
}
MongoClient.connect(url, async (err, client) => {
if (err) {
console.error(err);
return;
}
const db = client.db(dbName);
// Create a new user
const newUser: User = {
name: 'John Doe',
email: 'john.doe@example.com'
};
const result = await db.collection('users').insertOne(newUser);
console.log(`New user created with ID: ${result.insertedId}`);
// Find all users
const users = await db.collection('users').find().toArray();
console.log(`Found ${users.length} users`);
// Update a user
const userToUpdate = users[0];
userToUpdate.name = 'Jane Doe';
const updateResult = await db.collection('users').updateOne(
{ _id: userToUpdate._id },
{ $set: { name: user.name } }
);
console.log(Updated ${updateResult.modifiedCount} user);
// Delete a user
const deleteResult = await db.collection('users').deleteOne({ _id: userToUpdate._id });
console.log(Deleted ${deleteResult.deletedCount} user);
client.close();
});
This code creates a new `User` interface that represents a document in our MongoDB collection. We then create a new user, find all users, update a user, and delete a user.
Step 5: Compile and run the TypeScript code
Finally, we need to compile the TypeScript code and run it. Add the following script to the `package.json` file:
{
"scripts": {
"start": "tsc && node dist/index.js"
}
}This script runs the TypeScript compiler and then executes the compiled JavaScript code.
Run the following command to start the application:
npm startYou should see the following output in the console:
Connected to MongoDB at mongodb://localhost:27017
New user created with ID: 60997028e38f2d0f1b43d429
Found 1 users
Updated 1 user
Deleted 1 userCongratulations! You have successfully built a simple CRUD application using TypeScript and MongoDB.
Conclusion
In this tutorial, we learned how to set up a TypeScript project, connect to MongoDB, and perform CRUD operations on the database. TypeScript provides type-checking and improved code readability, making it a great choice for building Node.js applications that interact with MongoDB.