节点js mongodb数据库连接错误无法连接到服务器

时间:2017-11-10 12:07:37

标签: node.js database mongodb

  

C:\ mynodeprojects \ test>节点应用程序服务器启动300无法连接   首次连接时服务器[localhost:27017] [MongoError:geta ddrinfo   ENOENT localhost:27017]

包裹: -

{
  "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"
  }
}

数据库连接: -

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

1 个答案:

答案 0 :(得分:11)

请尝试使用此代码为我工作:

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

然后编写查询(例如查找uniqueId) -

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