连接到 MongoDB
1
创建您的Node.js应用程序
创建一个包含您的应用程序的文件,名为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);
完成这些步骤后,您将拥有一个可正常工作的应用程序,该应用程序使用驱动程序连接到您的MongoDB部署,在样本数据上运行查询,并打印出结果。
注意
如果在此步骤中遇到问题,请向以下社区论坛寻求帮助:MongoDB 社区论坛 或者通过使用本页右上角或右下角的评分此页面 选项卡提交反馈。