当我尝试 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/