var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/mongotest');
function validator(v) {
return v.length > 0;
}
var Post = new mongoose.Schema({
ua : { type: String, validate: [validator, "Empty Error"] },
created : { type: Date, default: Date.now }
});
exports.Post = db.model('Post', Post);
これでmongoの接続ができるようになった。
次にルーティングの部分を記述する。
/*
* GET home page.
*/
var model = require('../model');
var Post = model.Post;
exports.index = function(req, res) {
Post.find({}, function(err, items) {
res.render('index', { title: 'Entry List', items: items , num: items.length, ua : JSON.stringify(req.headers['user-agent']) })
});
};
exports.create = function(req, res){
console.log(req.body);
var newPost = new Post(req.body);
newPost.save(function(err){
if (err) {
console.log(err);
res.redirect('back');
} else {
res.redirect('/');
}
});
};
app.jsにルートを登録する。
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.post('/create', routes.create);
//app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});