node.js+express+mongodb

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   os   sp   java   for   

主要是想用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 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=‘/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加上。

  

 

node.js+express+mongodb

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.