Quick Start快速启动

This guide shows you how to create an application that uses the Node.js driver to connect to a MongoDB Atlas cluster. 本指南向您介绍如何创建一个使用Node.js驱动程序连接到MongoDB Atlas集群的应用程序。If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers.如果您希望使用不同的驱动程序或编程语言连接到MongoDB,请参阅我们的官方驱动程序列表

The Node.js driver is an interface through which you can connect to and communicate with MongoDB instances.js驱动程序是一个接口,您可以通过它连接到MongoDB实例并与之通信。

MongoDB Atlas is a fully-managed cloud database service that hosts your data on MongoDB instances. MongoDB Atlas是一个完全托管的云数据库服务,它在MongoDB实例上托管您的数据。We show you how to get started with your own free (no credit card required) instance in this guide.在本指南中,我们将向您展示如何开始使用您自己的免费(无需信用卡)实例。

Follow the steps below to connect your Node.js application with a MongoDB instance.按照以下步骤将Node.js应用程序连接到MongoDB实例。

Ensure your system has Node.js version 12 or later and a compatible version of npm (Node Package Manager) installed. 确保您的系统已安装Node.js版本12或更高版本以及兼容版本的npm(Node Package Manager)。For information on how to check your version of Node and npm, as well as installation instructions, see downloading and installing Node.js and npm.有关如何检查Node和npm版本的信息以及安装说明,请参阅下载和安装Node.js和npm

First, install Git using Git's Getting Started Guide.首先,使用Git的入门指南安装Git。

Then, in your shell, clone the js-starter repository:然后,在shell中克隆js-starter存储库

git clone https://github.com/mongodb-university/js-starter.git

Next, navigate into the repository:接下来,导航到存储库:

cd js-starter

Then, install the Node.js driver:然后,安装Node.js驱动程序:

npm install

This command performs the following actions:此命令执行以下操作:

  • Downloads and saves the mongodb package in a directory called node_modules下载mongodb包并将其保存在名为node_modules的目录中
  • Installs eslint, which the project uses to identify and report issues in your code安装eslint,项目使用它来识别和报告代码中的问题
  • Installs prettier, which the project uses to format your code安装prettier,项目使用它格式化代码

First, in your shell, create a directory for your project:首先,在shell中,为项目创建一个目录:

mkdir node_quickstart

Then, navigate into that directory:然后,导航到该目录:

cd node_quickstart

Next, initialize your project:

npm init -y
Tip
Why the -y?

If you specify the -y option in the command, npm uses the default values for your project settings. 如果在命令中指定-y选项,npm将使用项目设置的默认值。If you want to interactively select your project settings, omit the -y flag.如果要以交互方式选择项目设置,请忽略-y标志。

Then, install the Node.js driver:然后,安装Node.js驱动程序:

npm install mongodb

This command performs the following actions:

  • Downloads the mongodb package and the dependencies it requires
  • Saves the package in the node_modules directory
  • Records the dependency information in the package.json file

At this point, you are ready to use the MongoDB Node.js driver with your application.现在,您可以在应用程序中使用MongoDB Node.js驱动程序了。

After installing the MongoDB Node.js driver, create a MongoDB instance to store and manage your data. 安装MongoDB Node.js驱动程序后,创建一个MongoDB实例来存储和管理数据。Complete the Get Started with Atlas guide to set up a new Atlas account and a free tier cluster (MongoDB instance). 完成Atlas入门指南,以设置新的Atlas帐户和免费层集群(MongoDB实例)。Then, complete the Load Sample Data into Your Atlas Cluster guide to insert sample data into your cluster.然后,完成将样本数据加载到Atlas群集中指南,以将样本数据插入集群。

After completing the steps in these Atlas guides, you should have a new MongoDB cluster deployed in Atlas, a new database user, and sample datasets loaded into your cluster.完成这些Atlas指南中的步骤后,您应该在Atlas中部署一个新的MongoDB集群、一个新的数据库用户,并将示例数据集加载到集群中。

In this step, we create and run an application that uses the MongoDB Node.js driver to connect to your instance of MongoDB and run a query on the sample data.在这一步中,我们创建并运行一个应用程序,该应用程序使用MongoDB Node.js驱动程序连接到您的MongoDB实例,并对示例数据运行查询。

We pass instructions to the driver on where and how to connect to your MongoDB instance in a string called the connection string. 我们以一个称为连接字符串的字符串向驱动程序传递有关在何处以及如何连接到MongoDB实例的说明。This string includes information on the hostname or IP address and port of your instance, authentication mechanism, user credentials when applicable, and other connection options.此字符串包括有关实例的主机名或IP地址和端口、身份验证机制、用户凭据(如果适用)以及其他连接选项的信息。

If you are connecting to an instance or cluster that is not hosted by Atlas, see Other Ways to Connect to MongoDB for instructions on how to format your connection string.如果您连接到的实例或集群不是Atlas托管的,请参阅连接到MongoDB的其他方法,以获取有关如何格式化连接字符串的说明。

To retrieve your connection string for the instance and user you created in the previous step, log into your Atlas account and navigate to the Clusters section and click the Connect button for the cluster that you want to connect to as shown below.要检索在上一步中创建的实例和用户的连接字符串,请登录Atlas帐户并导航到“群集”部分,然后单击要连接到的群集的“连接”按钮,如下所示。

The connect button in the clusters section of the Atlas UI

Proceed to the Connect Your Application step and select the Node.js driver. 继续“连接应用程序”步骤并选择Node.js驱动程序。Select the Connection String Only tab and click the Copy button to copy the connection string to your clipboard as shown below.选择“仅连接字符串”选项卡,然后单击“复制”按钮将连接字符串复制到剪贴板,如下所示。

The connection string copy button in the Connection String Only tab of the Atlas UI

Save your connection string to a safe location that you can access in the next step.将连接字符串保存到下一步可以访问的安全位置。

Next, create a file to contain your application called index.js in your node_quickstart directory. 接下来,创建一个文件,将名为index.js的应用程序包含在node_quickstart目录中。Add the following code, replacing the uri variable with your connection string. 添加以下代码,用连接字符串替换uri变量。Make sure to replace the "<password>" section of the connection string with the password you created for your user that has atlasAdmin permissions.确保将连接字符串的“<password>”部分替换为您为具有atlasAdmin权限的用户创建的密码。

Tip

The line of code assigning the MongoClient variable uses Object destructuring, introduced to Node in v6. 分配MongoClient变量的代码行使用对象分解,这是v6中引入到Node的。If you are using an older version of Node, use the following to declare MongoClient.如果您使用的是旧版本的Node,请使用以下命令声明MongoClient

const MongoClient = require("mongodb").MongoClient;
const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。 const uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
const client = new MongoClient(uri);
async function run(){ try { await client.connect();
const database = client.db('sample_mflix'); const movies = database.collection('movies');
// Query for a movie that has the title 'Back to the Future'查询标题为“回到未来”的电影 const query = { title: 'Back to the Future' }; const movie = await movies.findOne(query);
console.log(movie); } finally { // Ensures that the client will close when you finish/error确保完成/出错时客户端将关闭 await client.close(); } } run().catch(console.dir);

Run the sample code with the following command from your command line:使用命令行中的以下命令运行示例代码:

node index.js

When you run the command, the sample code should output the details of the movie which resembles the following:运行命令时,示例代码应输出电影的详细信息,如下所示:

{
  _id: ...,
  plot: 'A young man is accidentally sent 30 years into the past...',
  genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
  ...
  title: 'Back to the Future',
  ...
}

If you receive an error, check whether you included the proper connection string in the application code, and loaded the sample dataset in your Atlas cluster.如果收到错误,请检查是否在应用程序代码中包含了正确的连接字符串,并将示例数据集加载到Atlas集群中。

After completing this step, you should have a working application that uses the Node.js driver to connect to your MongoDB instance, run a query on the sample data, and prints out the result.完成此步骤后,您应该有一个工作应用程序,该应用程序使用Node.js驱动程序连接到MongoDB实例,对示例数据运行查询,并打印出结果。

Learn how to read and modify data using the Node.js driver in our CRUD Operations guide or how to perform common operations in our usage examples.了解如何使用我们的CRUD操作指南中的Node.js驱动程序读取和修改数据,或者如何在用法示例中执行常见操作。