首页 > 代码库 > node.js+express+mongodb

node.js+express+mongodb

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

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

提交方法路径方法作用
getadd  
postadd 提交记录
getdel  
getmodify 转到修改页面
postmodify 修改记录

入口: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 setupapp.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 handlerapp.use(function(req, res, next) {    var err = new Error(‘Not Found‘);    err.status = 404;    next(err);});// error handlers// development error handler// will print stacktraceif (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 userapp.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=http://www.mamicode.com/‘/stylesheets/style.css‘ />"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="http://www.mamicode.com/submit"/>		<input type="reset" value="http://www.mamicode.com/reset"/>	</form>	  </body></html>

index.html:

<!DOCTYPE html><html>  <head>    <title><%= title %></title>    <link rel=‘stylesheet‘ href=http://www.mamicode.com/‘/stylesheets/style.css‘ />"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=http://www.mamicode.com/‘/stylesheets/style.css‘ />"post">		uid : <input type="text" name="uid" value="http://www.mamicode.com/"/><br/>		title:<input type="text" name="title" value="http://www.mamicode.com/"/><br/>		content:<textarea name="content"><%=demo.content%></textarea><br/>		<input type="hidden" name="id" value="http://www.mamicode.com/"/>				<input type="submit" value="http://www.mamicode.com/submit"/>		<input type="reset" value="http://www.mamicode.com/reset"/>	</form>  </body></html>

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

  

 

node.js+express+mongodb