node.js + express(ejs) + mongodb(mongoose) 增删改实例
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
express -e demo
2、初始化相关组件
var ejs = require(‘ejs‘); //增加
app.engine(‘html‘,ejs.__express); //增加
//将app.set(‘view engine‘, ‘ejs‘); 修改为app.set(‘view engine‘, ‘html‘);
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);//修改数据
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表,不知道是不是可以修改,反正我是这个认为的。
/*
* 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 = ‘