连接到mongodb时,connect不是函数

时间:2019-05-07 15:37:47

标签: 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 collection object
  client.close();
});

错误是:

client.connect(err => {
  ^

    TypeError: client.connect is not a function

我通过mongodb安装了npm,并将uri定义为他们给出的字符串。我还需要其他东西吗?

2 个答案:

答案 0 :(得分:1)

尝试以这种方式连接:

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);
});

答案 1 :(得分:0)

原因是您应该导入MongoClient类:

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

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