Zichen Ma
Zichen Ma

Reputation: 987

Node.js connect to MongoDB throw an error :MongoError: failed to connect to server [127.0.0.1:27017] on first connect

I am trying to use node.js to connect with mongodb on my windows system. However, it throw me an error:

C:\Users\mazic\Dropbox\Information System\CS602 Server Site Web Development\MongoDB_Practice\node_modules\mongodb\lib\mongo_client.js:225
          throw err
          ^
MongoError: failed to connect to server [127.0.0.1:27017] on first connect
    at null.<anonymous> (C:\Users\mazic\Dropbox\Information System\CS602 Server Site Web Development\MongoDB_Practice\node_modules\mongodb\node_modules\mongodb-core\lib\topologies\server.js:313:35)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at null.<anonymous> (C:\Users\mazic\Dropbox\Information System\CS602 Server Site Web Development\MongoDB_Practice\node_modules\mongodb\node_modules\mongodb-core\lib\connection\pool.js:260:12)
    at g (events.js:260:16)
    at emitTwo (events.js:87:13)
    at emit (events.js:172:7)
    at Socket.<anonymous> (C:\Users\mazic\Dropbox\Information System\CS602 Server Site Web Development\MongoDB_Practice\node_modules\mongodb\node_modules\mongodb-core\lib\connection\connection.js:162:49)
    at Socket.g (events.js:260:16)
    at emitOne (events.js:77:13)

and Here is my code:

"use strict";
const MongoClient = require('mongodb').MongoClient;

const dbUrl = 'mongodb://127.0.0.1:27017/cs602';

MongoClient.connect(dbUrl,  (err, db) => {
    if (err)
    {throw err}else {
        console.log('Successfully connected to',
            db.s.databaseName);
    }
    // Do database operations
    db.close();
});

Here is my file structure: enter image description here

I am new to node.js as well as mongodb, does anyone can help me with this? Thank you so much in advance!

Upvotes: 0

Views: 15401

Answers (1)

manuerumx
manuerumx

Reputation: 1250

This error could be caused by the MongoDB's bind IP setting. You can check MongoDB's config file. But the truth is i don't know is located in Windows systems.

In my case, the bind IP is set to localhost address, just as following:

# /usr/local/etc/mongod.conf
net:
  bindIp: 127.0.0.1

Upvotes: 2

Related Questions