首页 > 解决方案 > TypeError: 'connect' 只接受回调

问题描述

当我尝试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 服务”的输出

标签: node.jsmongodb

解决方案


这是因为您实际上是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


推荐阅读