我有以下代码:
var express = require('express'),
mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/bookAPI');
var Book = require('./models/bookModel');
var app = express();
var port = process.env.PORT || 3002;
var bookRouter = express.Router();
bookRouter.route('/Books')
.get(function(req,res){
Book.find(function(err,books){
if(err)
console.log(err);
else
res.json(books);
});
});
app.use('/api', bookRouter);
app.get('/', function(req, res){
res.send('welcome to my API!');
});
app.listen(port, function(){
console.log('Gulp is running my app on PORT: ' + port);
});
Bookmodel.js文件:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var bookModel = new Schema({
title: {
type: String
},
author: {type: String},
genre: {type: String},
read: {type: Boolean, default:false}
});
module.exports= mongoose.model('Book', bookModel);
我的gulpfile内容如下:
var gulp = require('gulp'),
nodemon = require('gulp-nodemon');
gulp.task('default', function(){
nodemon({
script: 'app.js',
ext: 'js',
env: {
PORT:8000
},
ignore: ['./node_modules/**']
})
.on('restart', function(){
console.log('Restarting');
});
});
然而,我一直遇到这个错误:
Gulp is running my app on PORT: 8000
events.js:85
throw er; // Unhandled 'error' event
^
Error: failed to connect to [localhost:27017]
at null.<anonymous> (/Users/admin/Documents/NodeAndExpress/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:549:74)
这非常令人沮丧,因为我正在密切跟进Pluralsight课程。我已经安装了所有必要的npm包等等。如果删除连接行,它肯定是mongoose连接引起错误。数据库还没有被创建,但讲师提到如果不存在,应该会自动创建。
我尝试了使用mongod
手动启动mongoose连接,但是我收到了错误:
ERROR: dbpath (/data/db) does not exist.
Create this directory or give existing directory in --dbpath.
mkdir /tmp/data; mongod --dbpath /tmp/data
。 - robertklep