📜  mongodb more 20 文档 - TypeScript (1)

📅  最后修改于: 2023-12-03 15:17:41.658000             🧑  作者: Mango

MongoDB + TypeScript

MongoDB is a popular NoSQL database that is widely used in modern web development. TypeScript is a powerful, typed superset of JavaScript that brings additional safety and user-friendly features to the language. In this tutorial, we'll take a look at how we can use MongoDB with TypeScript to build scalable and maintainable applications.

Installing MongoDB and TypeScript

Before we begin, we need to install MongoDB and TypeScript. To install MongoDB, please follow the instructions provided in the official documentation. To install TypeScript, you can use npm by running the following command:

npm install -g typescript
Setting up the project

First, let's create a new directory for our project and initialize a new Node.js project. We can create a new directory and navigate to it using the following commands:

mkdir mongodb-typescript
cd mongodb-typescript

Then, let's initialize a new Node.js project:

npm init

We will be using TypeScript, so let's create a new tsconfig.json file in the root directory:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "strict": true,
    "esModuleInterop": true
  }
}
Connecting to MongoDB

To connect to MongoDB, we need to use a library that provides a driver for MongoDB. In this tutorial, we'll be using the official MongoDB driver for Node.js.

First, let's install the driver:

npm install mongodb

Then, let's create a new file src/db.ts and define a function to connect to MongoDB:

import { MongoClient, Db } from 'mongodb';

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

export async function connect(): Promise<Db> {
  const client = await MongoClient.connect(url, { useNewUrlParser: true });
  return client.db(dbName);
}

The connect() function returns a Db object that we can use to interact with the database.

Creating models

In MongoDB, a collection can contain documents with different structures. TypeScript can help us define the structure of these documents using interfaces. Let's create a new file src/models.ts and define an interface for a Person document:

export interface Person {
  name: string;
  age: number;
}
Inserting data

Let's create a new file src/index.ts and write some code to insert a new Person document into the database:

import { connect } from './db';
import { Person } from './models';

async function test() {
  const db = await connect();
  const collection = db.collection<Person>('people');
  const person: Person = { name: 'Alice', age: 30 };
  const result = await collection.insertOne(person);
  console.log(result.insertedId);
}

test();

In this example, we connect to the database using the connect() function, then we use the db.collection<T>(name) method to get a reference to the people collection and specify the type of documents using the Person interface. We create a new Person object and insert it into the collection using the collection.insertOne() method. The result of the operation is a InsertOneWriteOpResult object that contains the ID of the inserted document.

Querying data

To query data from the database, we can use the collection.find() method. Let's modify the test() function to query the people collection and log the results:

async function test() {
  const db = await connect();
  const collection = db.collection<Person>('people');
  const cursor = collection.find();
  const people = await cursor.toArray();
  console.log(people);
}

In this example, we use the collection.find() method to obtain a cursor that points to all documents in the people collection. We then use the toArray() method to retrieve all documents and log them to the console.

Updating and deleting data

To update documents in the database, we can use the collection.updateOne() method. To delete documents, we can use the collection.deleteOne() method. Here's an example that updates and deletes a Person document:

async function test() {
  const db = await connect();
  const collection = db.collection<Person>('people');
  const person: Person = { name: 'Alice', age: 30 };

  // Insert the document
  const result = await collection.insertOne(person);
  const personId = result.insertedId;

  // Update the document
  await collection.updateOne({ _id: personId }, { $set: { age: 31 } });

  // Delete the document
  await collection.deleteOne({ _id: personId });
}
Conclusion

In this tutorial, we have demonstrated how to use MongoDB with TypeScript to build a simple application. We have covered the basics of connecting to MongoDB, defining models, inserting, querying, updating, and deleting documents. With TypeScript, we can ensure that our code is type-safe and helps us catch potential errors before they happen.