Javascript 连接到mongodb时,connect不是一个函数

Javascript 连接到mongodb时,connect不是一个函数,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,尝试从将代码连接到数据库的mongodb网站运行函数时出错 const MongoClient = require('mongodb') const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect(err => { const collection = client.db("test").collection("devices"); // perform actions on the

尝试从将代码连接到数据库的
mongodb
网站运行函数时出错

const MongoClient = require('mongodb')

const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});
错误是:

client.connect(err => {
  ^

    TypeError: client.connect is not a function

我已经通过
npm
安装了
mongodb
,并将uri定义为他们给出的字符串。我还需要什么吗

尝试以这种方式连接:

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

const uri = "yourUri...";
const databaseName = "yourDBName";

MongoClient.connect(uri, { useNewUrlParser: true }, (error, client) => {
  if (error) {
    return console.log("Connection failed for some reason");
  }
  console.log("Connection established - All well");
  const db = client.db(databaseName);
});

原因是您应该导入MongoClient类:

const MongoClient = require("mongodb").MongoClient;

而不是代码中的以下行:
const MongoClient=require(“mongodb”)

您从哪里获得示例代码?你能添加源代码吗?示例不会从
MongoClient
创建新对象,而是直接使用
MongoClient.connect()
执行
客户端的转储/insect
-其中是否有错误信息?是否为空?请检查下面的@jozev答案。你也可以使用destructuring
const{MongoClient}=require(“mongodb”)