Node js mongodb database connection error failed to connect to server

Question

C:\mynodeprojects\test>node app Sever start on 300 failed to connect to server [localhost:27017] on first connect [MongoError: geta ddrinfo ENOENT localhost:27017]

Package : -

{
  "name": "test",
  "version": "1.0.0",
  "description": "simple test app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "hukam thakur",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.2",
    "mongodb": "^2.2.33",
    "mongoose": "^4.10.8",
    "sudo": "^1.0.3"
  }
}

DB Connection here: -

var mongoose = require('mongoose');

var mongoURI = "mongodb://localhost:27017/test";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
  console.log("mongodb connection open");
}); 

Show source
| database   | node.js   | mongodb   2017-11-10 13:11 1 Answers

Answers to Node js mongodb database connection error failed to connect to server ( 1 )

  1. 2017-11-10 14:11

    Please Try this code it's work for me :

    var database,
    
    ObjectId = require('mongodb').ObjectID,
    
    MongoClient = require('mongodb').MongoClient,
    
    url = 'mongodb://localhost:27017/test',
    
    connection=MongoClient.connect(url, function(err, db) {  
      if (err) throw err;
      database=db;
    });
    

    Then write query like (eg for find uniqueId)-

    database.collection("users").findOne({_id:new ObjectId(userId)}, function(err, res) { 
     if (err) console.log(err);
       console.log(res);
    });  
    

Leave a reply to - Node js mongodb database connection error failed to connect to server

◀ Go back