Node.js脚本没有连接到localhost中的Mongodb数据库

时间:2016-06-03 07:22:23

标签: node.js mongodb

我有以下测试代码在创建rest api时运行mongodb和node.js

MONGO.JS 

var mongoose    =   require("mongoose");
mongoose.connect('mongodb://localhost/smartRideDb');
// create instance of Schema
var mongoSchema =   mongoose.Schema;
// create schema
var userSchema  = {
    "id"       : String,
    "email"    : String,
    "password" : String
};
// create model if not exists.
module.exports = mongoose.model('user',userSchema);

index.js定义为

var mongoOp =   require("./models/mongo");
var express = require('express');
var app     = express();

var bodyParser = require('body-parser');
var router     = express.Router();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));

app.use('/' , router);
var port = process.env.PORT || 3000;

/**
 * 
 * 
 * 
 */
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) 
{
  console.log("ERROR: " + reason);
  res.status(code || 500).json({"error": message});
}

/**
 * 
 * 
 * 
 */
router.get("/",function(req,res)
{
    res.json({"error" : false,"message" : "Hello World"});
});


//route() will allow you to use same path for different HTTP operation.
//So if you have same URL but with different HTTP OP such as POST,GET etc
//Then use route() to remove redundant code.

router.route("/users").get(function(req, res)
{
    var response = {};
    mongoOp.find({},function(err,data)
    {
        if(err) 
        {
            response = {"error" : true,"message" : "Error fetching data"};
        }
        else 
        {
            response = {"error" : false,"message" : data};
        }

        res.json(response);
    });
});


app.listen(port);
console.log("Listening to PORT " + port);

当我跑步时我得到这个错误

Muhammads-MBP:Api Umar$ node index.js
Listening to PORT 3000

/Users/Umar/Desktop/Projects On List Data/Creative Studios/School Ride/Api/node_modules/mongodb/lib/server.js:242
        process.nextTick(function() { throw err; })
                                      ^
Error: connect ECONNREFUSED 127.0.0.1:27017
    at Object.exports._errnoException (util.js:890:11)
    at exports._exceptionWithHostPort (util.js:913:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1057:14)

为什么mongodb没有得到

3 个答案:

答案 0 :(得分:2)

您可能希望尝试通过以下方式确保MongoDB已正确设置

  1. MongoDB已成功安装(OSX guide here
  2. 安装后在终端中运行mongod以运行MongoDB
  3. 在另一个终端中运行mongo,您应该可以看到类似的内容。
  4. MongoDB shell version: 3.2.4
    connecting to: test
    

答案 1 :(得分:0)

尝试在app.listen之前调用与mongo的连接,mongoose默认打开一个连接池来参加请求

mongoose.connect('mongodb://localhost/dbname', function(err) {
    if (err) throw err;
    app.listen(port);
    console.log("Listening to PORT " + port);
});

答案 2 :(得分:0)

最常见的问题排查步骤:

  1. 在某处错误地配置了localhost,因此请尝试将连接字符串更改为mongodb:// localhost:27017 / smartRideDb。
  2. 检查mongod是否在该端口运行。
  3. 检查是否有其他进程正在使用该端口。