我的示例代码在这里。我正在从developer_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 );
}
});
});
答案 0 :(得分:2)
你是否在本地安装和运行mongodb? 打开终端选项卡或窗口,然后运行mongo。
答案 1 :(得分:2)
当您在计算机上使用本地数据库时,您必须执行mongod(可以在已下载和解压缩的mongodb的bin文件夹中找到)。