首页 > 代码库 > nodejs+express+ejs+mongoose实例

nodejs+express+ejs+mongoose实例

nodejs+express+ejs+mongoose实例

nodejs学得异常痛苦,在这里将学的东西做一番整理,算是自我安慰吧。根据网上todo示例,用express和mongoose重写了部分代码,主要是业务逻辑这块(CRUD),这个没什么难度。目前尚未解决的问题是:express不能使用ejs layout template,查了好久也没解决,知道的麻烦告诉我一下。

一、代码目录

二、第三方模块

1、express

(1)express中文入门指引手册

(2)nodejs中文电子书

(3)如何在WebStorm中建立express工程?

 安装express

npm install express

安装成功后在node_modules下会找到express目录,同时也会找到.bin目录,它里面有express命令脚本

在终端下执行

express project_name

project_name为实际的nodejs工程名/路径 比如笔者:E:/Nodejs/todo

(4)Express官方文档

2、ejs

EJS快速入门教程

3、mongoose

mongoose2.7.0文档

Mongoose-让NodeJS更容易操作Mongodb数据库

三、核心介绍

1、使用mongoose写的dao(CRUD)

var util = require(‘util‘);var mongoose = require(‘mongoose‘);var Schema = mongoose.Schema;var dburl = require("../config").db;//数据库地址exports.connect = function(callback) {    mongoose.connect(dburl);}exports.disconnect = function(callback) {    mongoose.disconnect(callback);}exports.setup = function(callback) { callback(null); }//定义todo对象模型var TodoScheme = new Schema({    title:String    ,finished:{type:Boolean,default:false}    ,post_date:{type:Date,default:Date.now}});//访问todo对象模型mongoose.model(‘Todo‘, TodoScheme);var Todo = mongoose.model(‘Todo‘);//exports.emptyNote = { "_id": "", author: "", note: "" };exports.add = function(title,callback) {    var newTodo = new Todo();    newTodo.title = title;    newTodo.save(function(err){        if(err){            util.log("FATAL"+err);            callback(err);        }else{            callback(null);        }    });}exports.delete = function(id, callback) {    exports.findTodoById(id, function(err, doc) {        if (err)            callback(err);        else {            util.log(util.inspect(doc));            doc.remove();            callback(null);        }    });}exports.editTitle = function(id, title, callback) {    exports.findTodoById(id, function(err, doc) {        if (err)            callback(err);        else {            doc.post_date = new Date();            doc.title = title;            doc.save(function(err) {                if (err) {                    util.log(‘FATAL ‘+ err);                    callback(err);                } else                    callback(null);            });        }    });}exports.editFinished = function(id, finished, callback) {    exports.findTodoById(id, function(err, doc) {        if (err)            callback(err);        else {            doc.post_date = new Date();            doc.finished = finished;            doc.save(function(err) {                if (err) {                    util.log(‘FATAL ‘+ err);                    callback(err);                } else                    callback(null);            });        }    });}exports.allTodos = function(callback) {    Todo.find({}, callback);}exports.forAll = function(doEach, done) {    Todo.find({}, function(err, docs) {        if (err) {            util.log(‘FATAL ‘+ err);            done(err, null);        }        docs.forEach(function(doc) {            doEach(null, doc);        });        done(null);    });}var findTodoById = exports.findTodoById = function(id,callback){    Todo.findOne({_id:id},function(err,doc){        if (err) {            util.log(‘FATAL ‘+ err);            callback(err, null);        }        callback(null, doc);    });}

2、url路由控制

"use strict";var config = require(‘../config‘);var db = require(‘../dao/todoDao‘);exports.index = function (req, res, next) {    db.allTodos(function (err, todos) {        if (err) {            return next(err);        }        res.render(‘index.html‘, {todos: todos});    });};exports.new = function (req, res, next) {    var title = req.body.title || ‘‘;    title = title.trim();    if (!title) {        return res.render(‘error.html‘, {message: ‘标题是必须的‘});    }    db.add(title, function (err, row) {        if (err) {            return next(err);        }        res.redirect(‘/‘);    });};exports.view = function (req, res, next) {    res.redirect(‘/‘);};exports.edit = function (req, res, next) {    var id = req.params.id;    db.findTodoById(id, function (err, row) {        if (err) {            return next(err);        }        if (!row) {            return next();        }        res.render(‘todo/edit.html‘, {todo: row});    });};exports.save = function (req, res, next) {    var id = req.params.id;    var title = req.body.title || ‘‘;    title = title.trim();    if (!title) {        return res.render(‘error.html‘, {message: ‘标题是必须的‘});    }    db.editTitle(id,title,function (err, result) {        if (err) {            return next(err);        }        res.redirect(‘/‘);    });};exports.delete = function (req, res, next) {    var id = req.params.id;    db.delete(id, function (err) {        if (err) {            return next(err);        }        res.redirect(‘/‘);    });};exports.finish = function (req, res, next) {    var finished = req.query.status === ‘yes‘ ? true : false;    var id = req.params.id;    db.editFinished(id,finished, function (err, result) {        if (err) {            return next(err);        }        res.redirect(‘/‘);    });};

3、使用express框架

var express = require(‘express‘)  , todo = require(‘./controllers/todo‘)  , http = require(‘http‘)  , config = require("./config")  , todoDao = require("./dao/todoDao");var app = express();app.engine(‘html‘, require(‘ejs‘).renderFile);app.configure(function(){  app.set(‘port‘, config.port);  app.set(‘view engine‘, ‘ejs‘);  app.set(‘views‘, __dirname + ‘/views‘);  app.use(express.logger(‘dev‘));  app.use(express.bodyParser());  app.use(express.methodOverride());  app.use(app.router);  app.use(express.static(__dirname + ‘/public‘));});app.configure(‘development‘, function(){  app.use(express.errorHandler());});//url路由app.get(‘/‘, todo.index);app.post(‘/todo/new‘, todo.new);app.get(‘/todo/:id‘, todo.view);app.get(‘/todo/:id/edit‘, todo.edit);app.post(‘/todo/:id/edit‘, todo.save);app.get(‘/todo/:id/delete‘, todo.delete);app.get(‘/todo/:id/finish‘, todo.finish);todoDao.connect(function(error){    if (error) throw error;});app.on(‘close‘, function(errno) {    todoDao.disconnect(function(err) { });});http.createServer(app).listen(app.get(‘port‘), function(){  console.log("Express server listening on port " + app.get(‘port‘));});

注意点:为了在ejs中能使用.html,以下这句是关键,app.register()不能用了

app.engine(‘html‘, require(‘ejs‘).renderFile);

困惑点:如何在express中使用ejs的layout模板,具体是怎么设置的?!知道的麻烦说一下,谢谢~~~

四、源码

程序员不是求源码,就是求无码。

todo源码

nodejs+express+ejs+mongoose实例