Docs HomeNode.js

Connect to MongoDB连接到MongoDB

1

Create your Node.js Application创建Node.js应用程序

Create a file to contain your application called index.js in your node_quickstart project directory.node_quickstart项目目录中创建一个名为index.js的文件来包含应用程序。

Copy and paste the following code into the index.js file:将以下代码复制并粘贴到index.js文件中:

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

// Replace the uri string with your connection string.将uri字符串替换为连接字符串。
const uri = "<connection string uri>";

const client = new MongoClient(uri);

async function run() {
try {
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);
2

Assign the Connection String指定连接字符串

Replace the <connection string uri> placeholder with the connection string that you copied from the Create a Connection String step of this guide.<connection string uri>占位符替换为从本指南的创建连接字符串步骤中复制的连接字符串。

3

Run your Node.js Application运行Node.js应用程序

In your shell, run the following command to start this application:在您的shell中,运行以下命令来启动此应用程序:

node index.js

You should see the details of the retrieved movie document in the command line output:您应该在命令行输出中看到检索到的电影文档的详细信息:

{
_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 encounter an error or see no output, check whether you specified the proper connection string in the index.js file, and that you loaded the sample data.如果遇到错误或没有输出,请检查是否在index.js文件中指定了正确的连接字符串,以及是否加载了示例数据。

After you complete these steps, you should have a working application that uses the driver to connect to your MongoDB deployment, runs a query on the sample data, and prints out the result.完成这些步骤后,您应该有一个可工作的应用程序,它使用驱动程序连接到MongoDB部署,对样本数据运行查询,并打印出结果。

Note

If you run into issues on this step, ask for help in the MongoDB Community Forums or submit feedback using the Share Feedback tab on the right or bottom right side of this page.如果在此步骤中遇到问题,请在MongoDB社区论坛中寻求帮助,或使用此页面右侧或右下角的“共享反馈”选项卡提交反馈。

Next Steps