node.js+express+mongodb

主要是想用node.js链接mongodb,用的是mongoose。用ejs引擎,扩展到.html比较容易

小例子结构简单,框架清晰。

提交方法 路径 方法 作用
get add    
post add   提交记录
get del    
get modify   转到修改页面
post modify   修改记录

入口:mongodb.js,数据模型:model.js,(这两个在同一级目录) 路由:mong_ro.js(引入model.js用../)

三个页面index.html,add.html,modify.html

mongodb.js:

var express = require(‘express‘);
var path = require(‘path‘);
var favicon = require(‘serve-favicon‘);
var logger = require(‘morgan‘);
var cookieParser = require(‘cookie-parser‘);
var bodyParser = require(‘body-parser‘);
var routes = require(‘./routes/mong_ro‘);
var users = require(‘./routes/users‘);

var app = express();

// view engine setup
app.set(‘views‘, path.join(__dirname, ‘views‘));
app.set(‘view engine‘, ‘ejs‘);
app.engine(‘html‘, require(‘ejs‘).renderFile);

// uncomment after placing your favicon in /public
// app.use(favicon(__dirname + ‘/public/favicon.ico‘));
app.use(logger(‘dev‘));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, ‘public‘)));
app.use(‘/‘, routes);
app.use(‘/users‘, users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error(‘Not Found‘);
    err.status = 404;
    next(err);
});

// error handlers
// development error handler
// will print stacktrace
if (app.get(‘env‘) === ‘development‘) {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render(‘error‘, {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render(‘error‘, {
        message: err.message,
        error: {}
    });
});

module.exports = app;

model.js:

var express = require(‘express‘)
	, routes = require(‘./routes‘)
	, mongoose = require(‘mongoose‘)
	, Schema = mongoose.Schema;

var demoSchema = new Schema({
	uid: String,
	title: String,
	content: String,
	createTime: {type:Date, default: Date.now}
});

exports.Demo = mongoose.model(‘blog‘, demoSchema);

mong_ro.js:

var express = require(‘express‘)
    , router = express.Router()
	, mongoose = require(‘mongoose‘)
	, model = require(‘../model‘)
	, Demo = model.Demo;

mongoose.connect(‘mongodb://localhost/blog‘);

/* GET home page. */
// router.get(‘/‘, function(req, res) {
//   res.render(‘index‘, { title: ‘Express‘ });
// });

router.get(‘/‘, function(req, res) {
  Demo.find(function(err, docs){
		res.render(‘index.html‘, {
			title:‘Express Demo Example‘,
			demos:docs
		});
	});
});

router.get(‘/add‘, function(req, res) {
    res.render(‘add.html‘, {title:‘add demo list‘});
});

router.post(‘/add‘, function(req, res) {
  var demo = new Demo({
		uid: req.body.uid,
		title: req.body.title,
		content: req.body.content
	});
	demo.save(function(err, doc){
		res.redirect(‘/‘);
	})
});

router.get(‘/del‘, function(req, res){
	var id = req.query.id;
	if(id && ‘‘ != id){
		Demo.findByIdAndRemove(id, function(err, docs){
			res.redirect(‘/‘);
		});
	}
});

router.get(‘/modify‘, function(req, res) {
	var id = req.query.id;
	if(id && ‘‘ != id){
		Demo.findById(id ,function(err, docs){
			res.render(‘modify.html‘, {title:‘修改‘, demo:docs});
		});
	}
});

router.post(‘/modify‘, function(req, res) {
  var demo = {
		uid : req.body.uid,
		title: req.body.title,
		content : req.body.content
	};	
	var id = req.body.id; 
	if(id && ‘‘ != id) {
		Demo.findByIdAndUpdate(id, demo,function(err, docs) {
			res.redirect(‘/‘);
		});
	}
});

//post方法总会先构建demo对象
//demo的方法:find,save,findByIdAndRemove,findById,findByIdAndUpdate
//get请求,用req.query.id;post请求,用req.body.id.

module.exports = router;

add.html:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel=‘stylesheet‘ href=‘/stylesheets/style.css‘ />
  </head>
  <body>
	<h1>增加</h1>	
	<form method="post">
		uid : <input type="text" name="uid"/><br/>
		title:<input type="text" name="title"/><br/>
		content:<textarea name="content"></textarea><br/>		
		<input type="submit" value="submit"/>
		<input type="reset" value="reset"/>
	</form>	
  </body>
</html>

index.html:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel=‘stylesheet‘ href=‘/stylesheets/style.css‘ />
	<style type="text/css">
	table { border:1px solid green;}
	table thead tr th{ border:1px solid green;}
	table tbody tr td{ border:1px solid green;}
	</style>	
  </head>
  <body>
	<p><a href="http://localhost:3000/add">增加</a></p>
    <h1>DEMO List</h1>	
	<table>
		<thead>
			<tr>
				<th>id</th>
				<th>uid</th>
				<th>title</th>
				<th>content</th>
				<th>createTime</th>
				<th>操作</th>
			</tr>
		</thead>
		<tbody>			
			<% demos.forEach(function( demo ){ %>
			<tr>
				<td><%=demo._id%></td>
				<td><%= demo.uid %></td>
				<td><%= demo.title %></td>
				<td><%= demo.content %></td>
				<td><%=demo.createTime%></td>
				<td><a href="http://localhost:3000/del?id=<%=demo._id%>">Delete</a> | <a href="http://localhost:3000/modify?id=<%=demo._id%>">Update</a></td>
			</tr>
			<% }); %>
		</tbody>
	</table>
  </body>
</html>

modify.html:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel=‘stylesheet‘ href=‘/stylesheets/style.css‘ />
  </head>
  <body>
	<h1>修改</h1>
	<form method="post">
		uid : <input type="text" name="uid" value="<%=demo.uid%>"/><br/>
		title:<input type="text" name="title" value="<%=demo.title%>"/><br/>
		content:<textarea name="content"><%=demo.content%></textarea><br/>
		<input type="hidden" name="id" value="<%=demo._id%>"/>		
		<input type="submit" value="submit"/>
		<input type="reset" value="reset"/>
	</form>
  </body>
</html>

在此基础上可以不断扩展,把学会的bootstrap加上,把好用的jquery UI加上。

  

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。