Nodejs+express+ejs+mongoose instances

Source: Internet
Author: User
Tags call back

Nodejs+express+ejs+mongoose instances

Nodejs learning is extremely painful, here will learn something to do a tidy, is self comfort it. According to the online Todo example, with Express and Mongoose rewrite part of the code, mainly business logic this piece (CRUD), this is no difficulty. The problem that has not been solved at present is: Express cannot use Ejs layout template, check for a long time did not solve, know the trouble to tell me.

First, the Code directory

Second, third-party modules

1. Express

(1) Express Chinese Starter Guide

(2) Nodejs Chinese e-book

(3) How to set up Express project in Webstorm?

Install Express

NPM Install Express

After successful installation, the Express directory will be found under Node_modules and will also find the. bin directory, which has express command script

Execute under the terminal

Express PROJECT_NAME

Project_Name for the actual Nodejs project name/path such as Author: E:/nodejs/todo

(4) Express official documents

2, Ejs

Ejs Quick Start Tutorial

3, Mongoose

mongoose2.7.0 Documentation

Mongoose-makes Nodejs easier to manipulate MongoDB database

Three, the core introduction

1. DAO (CRUD) written with Mongoose

var util = require (' util '); var mongoose = require (' Mongoose '); var Schema = Mongoose. Schema;var Dburl = require (".. /config "). db;//database Address Exports.connect = function (callback) {mongoose.connect (dburl);} Exports.disconnect = function (callback) {Mongoose.disconnect (callback);} Exports.setup = function (callback) {callback (null);} Define the Todo object model var todoscheme = new Schema ({title:string, finished:{type:boolean,default:false}, Post_date:{type:da Te,default:date.now});//Access Todo object Model 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) call BacK (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 (' FA            TAL ' + 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 (er            R) {util.log (' FATAL ' + err);        Callback (err, NULL);    } callback (null, DOC); });}

2. URL Routing Control

"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: ' title is required '});        } 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: ' title is required '});        } 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. Using the Express framework

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 Route 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 (ERR) { });}); Http.createserver (APP). Listen (App.get (' Port '), function () {Console.log ("Express Server listening on port" + app.get (' Port '));

Note: In order to be able to use the. html in Ejs, the following sentence is the key, App.register () can not be used

App.engine (' HTML ', require (' Ejs '). RenderFile);

Confusion point: How to use Ejs layout template in Express, how to set it?! Know the trouble to say, thank you ~ ~ ~

Iv. Source Code

The programmer is not seeking the source code, is seeking uncensored.

Todo Source

Nodejs+express+ejs+mongoose instances

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.