0Pricing
Node.js Backend Development Bootcamp · 课时

将 Node.js 连接到 MongoDB

配置 MongoDB,将 Node.js 应用连接到 MongoDB,并了解数据库基础概念。

将 Node.js 连接到 MongoDB 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Welcome to MongoDB

In this lesson, we'll dive into MongoDB, a popular NoSQL database, and learn how to connect your Node.js applications to it.

Databases are essential for storing and organizing data in almost any modern application. Let's get started!

NoSQL vs. SQL Databases

Before MongoDB, let's understand its place:

  • SQL Databases (Relational): Use tables with fixed schemas, like PostgreSQL or MySQL. Data is structured in rows and columns.
  • NoSQL Databases (Non-Relational): Offer more flexible data models. MongoDB is a document database, meaning it stores data in flexible, JSON-like documents.

NoSQL databases are often chosen for their scalability and flexibility.

MongoDB: Documents & Collections

MongoDB's core concepts are simple:

  • Documents: These are the basic units of data, similar to rows in SQL tables, but they are JSON-like objects. They can contain various data types and nested structures.
  • Collections: These are groups of documents, similar to tables in SQL. A collection does not enforce a fixed schema, allowing documents within the same collection to have different fields.

Think of a document as a single record, and a collection as a folder holding related records.

Setting Up MongoDB

To connect Node.js, you need a running MongoDB instance. You have a few options:

  • Local Installation: Download and install MongoDB Community Server on your machine.
  • MongoDB Atlas: A cloud-based database service (DBaaS) that provides a free tier. This is often the easiest way to get started without local setup.

For this lesson, we'll assume a local instance running on its default port, or an Atlas cluster you've configured.

The `mongodb` Driver

To interact with MongoDB from Node.js, we use the official mongodb driver. This library provides all the necessary tools to connect, query, and manage your data.

It acts as a bridge, allowing your JavaScript code to communicate seamlessly with the MongoDB server.

Installing the Driver

First, navigate to your project directory in the terminal and install the mongodb package using NPM:

  • npm init -y (if starting a new project)
  • npm install mongodb

This command adds the mongodb package to your project's dependencies.

First MongoDB Connection

Let's write a simple Node.js script to connect to a MongoDB instance. This example will connect to a local server and then close the connection.

Try running this example:

const { MongoClient } = require('mongodb');

// Connection URI for a local MongoDB instance
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

async function connectToMongo() {
  try {
    await client.connect(); // Connect to the MongoDB server
    console.log("Connected successfully to MongoDB!");
  } catch (err) {
    console.error("Failed to connect to MongoDB:", err);
  } finally {
    await client.close(); // Ensure the connection is closed
    console.log("Connection closed.");
  }
}

connectToMongo();

Understanding the URI

The connection URI (e.g., mongodb://localhost:27017) is crucial. Let's break it down:

  • mongodb://: The protocol indicating a MongoDB connection.
  • localhost: The hostname or IP address where MongoDB is running. For cloud services like Atlas, this would be a specific server address.
  • 27017: The default port number for MongoDB.
  • /mydb (Optional): You can specify a database name directly in the URI. If omitted, you connect to the server and can then select a database.

For Atlas, your URI will include username, password, and cluster details.

Handling Connection Events

It's good practice to handle potential connection errors and events. The MongoClient emits events you can listen to:

  • client.on('error', ...): Catches errors during connection or operations.
  • client.on('close', ...): Fired when the connection to the server is closed.
  • client.on('reconnect', ...): Emitted if the driver successfully reconnects after a disconnection.

Using try...catch...finally blocks with async/await, as shown, is a modern way to manage connection flow.

Quick Check: Connection URI

You've seen how a MongoDB connection URI is structured.

Recap: Connecting Node.js to MongoDB

Great job! You've taken the first step into data persistence with Node.js and MongoDB.

  • We learned about NoSQL databases and MongoDB's document/collection model.
  • You now know how to install and use the official mongodb driver.
  • We explored how to establish a connection using a connection URI and handle basic connection flow.

Next, we'll dive deeper into modeling your data with Mongoose!

常见问题解答

「将 Node.js 连接到 MongoDB」课时是免费的吗?

是的 — 「将 Node.js 连接到 MongoDB」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

「将 Node.js 连接到 MongoDB」这节课中我会学到什么?

配置 MongoDB,将 Node.js 应用连接到 MongoDB,并了解数据库基础概念。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Node.js Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「将 Node.js 连接到 MongoDB」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 将 Node.js 连接到 MongoDB
  2. 用于数据建模的 Mongoose ODM
  3. 使用 Mongoose 执行 CRUD 操作
  4. 使用 Mongoose 查询与筛选数据
← 返回 Node.js Backend Development Bootcamp