连接 Mongo DB 后节点服务器崩溃

时间:2021-07-25 09:13:00

标签: node.js mongodb express

我正在尝试将 MongoDB 与我的 Node 服务器连接。我创建了一个集群并将以下代码复制到我的文件中:

const { MongoClient } = require('mongodb');
const uri = "mongodb+srv://myDb:<password>@cluster0.3kehi.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

Here is how it looks like in my index file

但是,我的服务器在这之后崩溃了,我收到了这个错误。

Click here to see the error I am getting

这可能是一个基本问题,但我是 mongo DB 的新手。我该如何解决?谁能解释为什么我会收到这个错误?

1 个答案:

答案 0 :(得分:1)

此错误发生在您在导出之前使用 MongoClient 的第 5 行。然后在第 16 行导入它。只需在开始时导入您需要的每个模块或文件。它会起作用