node.js - 类型错误 : 'connect' only accepts a callback

标签 node.js mongodb

当我尝试 node index.js 时,我的错误来自 TypeError: 'connect' only accepts a callback ,然后我对如何解决这个问题感到困惑。
错误转到 mongo_client.js:165:11

我做了一个关于如何使用 Nodejs 连接到 mongodb 的教程,但是,我发现了一个 ppl 从未遇到过的问题

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient();
const url = 'mongodb://localhost:27107/testedmtdev';

MongoClient.connect(url, function(err, client){
    if(err){
        console.log('Unable to connect to the Mongodb server. Error : ', err);
    } else {
app.listen(3000, ()=>{
            console.log('Connected to mongodb, webservice running on port 3000');
        })
    }
});

我期望“连接到 mongodb,在端口 3000 上运行的 web 服务”的输出

最佳答案

这是因为您实际上是在不带参数的情况下调用 MongoClient

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient();  // <-- your calling the method here

进行更改以仅使用引用
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;  // <-- do *not* call method

https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect

关于node.js - 类型错误 : 'connect' only accepts a callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56625122/

相关文章:

node.js - nodejs 中的 bittorrent tracker seeder 和 leecher

node.js - MongoDB 生产验证失败

Windows:应用程序无法正常启动(0xc000007b)

c# - 在Docker中连接到mongodb

node.js - 每天在特定时间在javascript中触发一个函数

node.js - 如何将 mongo 字符串解析为 nodejs 中的对象?

javascript - 如何访问我从客户端(NodeJs)发布的数据

node.js - 如何在 Node 8 的 Node.js REPL 中导入 ES 模块?

javascript - 测试异步调用会在 Node JS 中抛出未处理的 promise 拒绝

Mongodb聚合查询对累积值进行减法和分组