使用node express框架连接mongodb

时间:2016-04-23 03:48:48

标签: node.js mongodb

我是mongodb和node.js的新用户。我在尝试运行node.js应用程序时出现以下错误,错误日志似乎mongodb实例拒绝了我的请求:

 Error: connect ECONNREFUSED 127.0.0.1:27017
    at Object.exports._errnoException (util.js:856:11)
    at exports._exceptionWithHostPort (util.js:879:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1053:14)
 Press any key to continue...

以下是我用来连接mongodb的app.js的代码:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Create a reference to mongoose
var mongoose = require('mongoose');


var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// Open a connection to the DB. Here bookAPI is the name of database.
var db = mongoose.connect('mongodb://127.0.0.1:27017/bookAPI');

// Create a reference to models
var Book = require('./models/bookModel');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

2 个答案:

答案 0 :(得分:1)

127.0.0.1:27017上没有mongodb服务。
您应该首先启动mongodb服务或更改您的配置以连接现有的mongodb服务。

答案 1 :(得分:1)

mongoose.connect('mongodb://localhost/bookAPI');

确实,服务(例如:mongod)应该是活跃的。

确保您的mongodb服务正在运行。