文档菜单
文档首页
/ / /
Node.js 驱动程序
/

连接到 MongoDB

1

创建一个包含您的应用程序的文件,名为index.js,位于您的node_quickstart项目目录中。

将以下代码复制并粘贴到index.js文件中

const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
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

<connection string uri>占位符替换为您从本指南的创建连接字符串步骤中复制的连接字符串。创建连接字符串

3

在您的shell中,运行以下命令以启动此应用程序

node index.js

输出包括检索到的电影文档的详细信息

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

如果您遇到错误或没有输出,请检查您是否在index.js文件中指定了正确的连接字符串,并且是否已加载示例数据。

完成这些步骤后,您将拥有一个可正常工作的应用程序,该应用程序使用驱动程序连接到您的MongoDB部署,在样本数据上运行查询,并打印出结果。

注意

如果在此步骤中遇到问题,请向以下社区论坛寻求帮助:MongoDB 社区论坛 或者通过使用本页右上角或右下角的评分此页面 选项卡提交反馈。

返回

创建连接字符串