1
votes

hello dear community im wondering myself why i get this error when i try to use mongodb and nodejs.

const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
    if (err) {
        console.log('Unable to connect to MongoDB server.')
    }else{
        console.log('Connected to MongoDB server.')
    }
    db.close();
});

Output in the console:

Unable to connect to MongoDB server. C:\Users\eljubec\Desktop\node-todo-api\node_modules\mongodb\lib\mongo_client.js:421 throw err ^

TypeError: Cannot read property 'close' of null at MongoClient.connect (C:\Users\eljubec\Desktop\node-todo-api\playground\mongodb-connect.js:9:8) at connectCallback (C:\Users\eljubec\Desktop\node-todo-api\node_modules\mongodb\lib\mongo_client.js:527:5) at C:\Users\eljubec\Desktop\node-todo-api\node_modules\mongodb\lib\mongo_client.js:418:11 at process._tickCallback (internal/process/next_tick.js:150:11)

1
If the connection fails, db is going to be null. Move the close command inside your else block. - Chris G
Obviously there is a problem connecting to MongoDB. Why don't you log err to see what it is? - str
try to add "console.log(err)" in your first if statment and show us the result - Abslen Char
As the other comments said: Your output is showing an err connecting to the database. When the database doesn't connect, your db object is going to be null, and therefore not have a close method. - Cody Haines
{ MongoError: connection 0 to localhost:27017 timed out name: 'MongoError', message: 'connection 0 to localhost:27017 timed out' } - dsds

1 Answers

4
votes

You might want to check if your MongoDB service is up and running on the given port. Open a Command Prompt (WindowsKey+R->cmd->OK) and run the following command:

netstat -a | find "27017"

This should give you some output like this:

TCP    127.0.0.1:27017        <MACHINE_NAME>:0         LISTENING

If you don't see this line you need to start MongoDB or make sure it runs on the default port.

The second error "Cannot read property 'close' of null" is simply because the connection fails so your db variable will hold a null value according to the docs which obviously you cannot run a close() on. You might want to move that close() statement inside the else statement.