Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'connect' only accepts a callback

when I try node index.js my error comes with TypeError: 'connect' only accepts a callback, then I'm confused about how to solve this problem. The error goes to mongo_client.js:165:11

I did a tutorial about how to connect to mongodb with Nodejs but, I found a problem that ppl never had since now

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

I expect the output of 'Connected to mongodb, webservice running on port 3000'

like image 706
Timoteus Ivan Avatar asked Dec 11 '22 02:12

Timoteus Ivan


1 Answers

It's because you're actually calling MongoClient with no parameters.

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

Make a change to just use a reference

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

like image 131
VtoCorleone Avatar answered Jan 05 '23 00:01

VtoCorleone