码迷,mamicode.com
首页 > 数据库 > 详细

node.js + express(ejs) + mongodb(mongoose) 增删改实例

时间:2015-09-21 00:03:59      阅读:428      评论:0      收藏:0      [点我收藏+]

标签:

刚学node不久,以下是对最近学习的总结,不足的地方还请见谅。

 

node 和 mongodb安装不做为本文讲解,想了解的朋友可以通过一下链接配置环境:

 

node 安装:http://www.infoq.com/cn/articles/nodejs-npm-install-config

Win7下MongoDB安装 :http://www.mkyong.com/mongodb/how-to-install-mongodb-on-windows/

MongoDB 安装步骤总结:


1、解压目录到d盘 mongodb

2、安装目录的下新建文件mongo.config文件

 

##store data here

dbpath=D:\mongodb\data

 

##all output go here

logpath=D:\mongodb\log\mongo.log

 

##log read and write operations

diaglog=3

3、d:\mongodb\bin>mongod --config D:\mongodb\mongo.config

4、d:\mongodb\bin> mongod --config D:\mongodb\mongo.config --install

net start MongoDB
net stop MongoDB
mongod --remove

1、创建node项目

express -e demo

2、初始化相关组件

npm install

// 初始化ejs

npm install ejs

// 初始化express组件

npm install express

// 初始化mongdb组合的组件 

npm install mongoose

npm install express-mongoose

// node 默认启动后修改文件,页面不会立即体现,通过该组件可以使修改的文件实时在页面体现出来

npm install supervisor

3、运行app.js,访问:http://localhost:3000,查看页面,如看到以下页面则说明页面访问成功:

技术分享                       

 

4、此时项目默认使用*.ejs作为页面的模板,为了方便我们吧ejs的后缀修改html

a) 修改app.js中内容:

var ejs = require(‘ejs‘); //增加

app.engine(‘html‘,ejs.__express); //增加

//将app.set(‘view engine‘, ‘ejs‘); 修改为app.set(‘view engine‘, ‘html‘);

 技术分享

 

b) 重命名views下的index.ejs为index.html

 

5、重新启动服务访问,如果页面可以正常显示则说明修改成功。

 

6、现在开始写增删改查的详细方法

 

      1)修改路由(app.js)

app.get(‘/add.html‘,routes.add); //跳转到添加页面
app.post(‘/add.html‘, routes.create);//添加记录
app.get(‘/del.html‘,routes.delById);//删除
app.get(‘/modify.html‘, routes.toModify); //跳转到修改页面
app.post(‘/modify.html‘, routes.modify);//修改数据

      2)在routes目录下创建model.js文件,内容如下:

var mongoose = require(‘mongoose‘);
var Schema = mongoose.Schema;

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

exports.Demo = mongoose.model(‘Demo‘,demoSchema); //此处Demo会自动对应数据库中的demos表,不知道是不是可以修改,反正我是这个认为的。

      3)修改index.js,添加逻辑方法

/*
 * GET home page.
 */
var mongoose = require(‘mongoose‘);
var model = require(‘./model‘);
var Demo = model.Demo;

mongoose.connect(‘mongodb://localhost/monkey‘);
 
exports.index = function(req, res){
            //查询所有数据,保存到demos中,在页面循环输出
            Demo.find(function(err,docs){
                        res.render(‘index‘, {
                                     title:‘Express Demo Example‘,
                                     demos:docs
                        });
            });
           
};

//跳转到添加页面
exports.add = function(req, res) {
            console.log(‘----here‘);
            res.render(‘add.html‘, {title :‘添加 demo list‘});
};

//创建新纪录
exports.create = function(req, res){
            var demo = new Demo({
                        uid : req.body.uid,
                        title: req.body.title,
                        content : req.body.content
            });
           
            console.log(‘create----‘);
            demo.save(function(err,doc){
                        console.log(doc);
                        res.redirect(‘/‘);
            });

};

// 根据id删除相应的记录
exports.delById = function(req, res) {
           
            var id = req.query.id;
            console.log(‘id = ‘ + id);
           
            if(id && ‘‘ != id) {
                        console.log(‘----delete id = ‘ + id);
                        Demo.findByIdAndRemove(id, function(err, docs) {
                                     console.log(‘delete-----‘+ docs);
                                     res.redirect(‘/‘);
                        });
            }
           
};

// 查询对应修改记录,并跳转到修改页面
exports.toModify = function(req, res) {
            var id = req.query.id;
            console.log(‘id = ‘ + id);
           
            if(id && ‘‘ != id) {
                        console.log(‘----delete id = ‘ + id);
                        Demo.findById(id, function(err, docs){
                                     console.log(‘-------findById()------‘ + docs);
                                    
                                     res.render(‘modify.html‘,{title:‘修改ToDos‘,demo:docs});
                        });
            };
};

//修改相应的值
exports.modify = function(req, res) {
           
            var demo = {
                        uid : req.body.uid,
                        title: req.body.title,
                        content : req.body.content
            };
           
            var id = req.body.id; //因为是post提交,所以不用query获取id
            if(id && ‘‘ != id) {
                        console.log(‘----update id = ‘ + id + "," + demo);
                        Demo.findByIdAndUpdate(id, demo,function(err, docs) {
                                     console.log(‘update-----‘+ docs);
                                     res.redirect(‘/‘);
                        });
            }
           
};

      4)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://houzhiqingjava.blog.163.com/blog/add.html">增加</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://houzhiqingjava.blog.163.com/blog/del.html?id=<%=demo._id%>">Delete</a> | <a href="http://houzhiqingjava.blog.163.com/blog/modify.html?id=<%=demo._id%>">Update</a></td>
                                     </tr>
                                     <% }); %>
                        </tbody>
            </table>
  </body>
</html>

      5)add.html页面

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel=‘stylesheet‘ href=‘/stylesheets/style.css‘ />
           
            <style type="text/css">

            </style>
  </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>

      6) 修改页面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>

 

到此,增删改查已经完成,启动项目即可。

 

node.js + express(ejs) + mongodb(mongoose) 增删改实例

标签:

原文地址:http://www.cnblogs.com/smallstupidwife/p/4824701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!