Zichen Ma Zichen Ma - 1 year ago 552
Node.js Question

Node.js connect to MongoDB throw an error :MongoError: failed to connect to server [] 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 [] 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://';

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

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!

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download