日期:2014-05-16 浏览次数:20406 次
var express = require('express');
var mongodb = require('mongodb');
var http = require('http');
var path = require('path');
var settings = require('./settings');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var db;
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
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());
}
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/test", function(err, database) {
if(err) throw err;
db = database;
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
app.get("/", function(req, res) {
db.collection("test").find({}, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
res.render('index', { title: 'Express' });
});
app.get("/add", function(req, res) {
res.render('add', { });
});
app.post("/add", function(req, res) {
var json = req.body.json;
db.collection("test").insert(json, function(err, doc){
if(err)
console.error(err);
else
console.log("OK!"+doc);
});
res.end();
});