node.js - [错误 : failed to connect to [localhost:27017]] . 此错误发生在 mongodb 上

标签 node.js mongodb mongoose

<分区>

我的示例代码在这里。我正在从书 developing_backbone.js_applications 中学习 我已经在我的电脑上安装了 mongodb。我在这个网站上搜索了答案,但没有任何线索。 有没有人有任何解决方案?谢谢!

// Module dependencies.
var application_root = __dirname,
    express = require('express'), //Web framework
    path = require('path'), //Utilities for dealing with file paths
    mongoose = require('mongoose'); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure(function () {
    //parses request body and populates request.body
    app.use(express.bodyParser());
    //checks request.body for HTTP method overrides
    app.use(express.methodOverride());
    //perform route lookup based on URL and HTTP method
    app.use(app.router);
    //Where to serve static content
    app.use(express.static(path.join(application_root, 'site')));
    //Show all errors in development
    app.use(express.errorHandler({
        dumpExceptions: true,
        showStack: true
    }));
});


//Start server
var port =4711;
app.listen(port, function () {
    console.log('Express server listening on port %d in %s mode',
        port, app.settings.env);
});

// Routes
app.get( '/api', function( request, response ) {

    response.send( 'Library API is running and the requestis' );
});

//Connect to database
mongoose.connect( 'mongodb://localhost/library_database', function(err) { if (err) console.log(err); } );
//Schemas
var Book = new mongoose.Schema({
    title: String,
    author: String,
    releaseDate: Date
});
//Models
var BookModel = mongoose.model( 'Book', Book );

//Get a list of all books
app.get( '/api/books', function( request, response ) {
    return BookModel.find( function( err, books ) {
        if( !err ) {
            return response.send( books );
        } else {
            return console.log( err );
        }
    });
});

最佳答案

您是否在本地安装并运行了 mongodb? 让终端选项卡或窗口保持打开状态,并在其中运行 mongo。

关于node.js - [错误 : failed to connect to [localhost:27017]] . 此错误发生在 mongodb 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23946865/

相关文章:

javascript - 如何使用javascript在txt文件的新行中打印对象数组的每个对象?

node.js - 如何在 Passport.js 中定义多个 isAuthenticated 函数?

node.js - 我已经在 mongoose 上加载了一个文档后,我可以填充更多字段吗?

node.js - html-webpack-plugin - 如何在不执行 EJS 模板的情况下插入 webpack bundle.js

javascript - 为什么 NodeJS 将我的对象键字符串转换为对象文字?

javascript - Node.js 中的 MongoDB 分页(带排序)

javascript - Express JS - 无法将数组推送到 MongoDB 中的表

arrays - 删除数组中的值(MongoDB 和 mongoose)

node.js - 如何允许用户更新他们的个人资料?

node.js - 在 Node/Express 应用程序中使用 Mongoose/MongoDB 从一个模型填充到另一个模型