第一个简单的例子
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://127.0.0.1:27017');
db.once('open',function(callback){
console.log('数据库成功连接');
})
module.exports = db;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="/doadd" method="get">
<p>书名:<input type="text" name="name" /></p>
<p>作者:<input type="text" name="author" /></p>
<p>价格:<input type="text" name="price"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
<!-- index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
table,tr,td{
border:1px solid red;
}
</style>
</head>
<body>
<a href="/addbook">增加图书</a>
<table>
<tr>
<td>oid</td>
<td>图书名字</td>
<td>作者</td>
<td>价格</td>
<td>操作</td>
</tr>
<% for(var i = 0;i < tushu.length; I==){%>
<tr>
<td><%=tushu[i]._id%></td>
<td><%=tushu[i].name%></td>
<td><%=tushu[i].author%></td>
<td><%=tushu[i].price%></td>
<td><a href="/edit?id<%=tushu[i]._id%>"></a></td>
</tr>
<%=tushu[i].price%>
</table>
</body>
</html>
//app.js
var express = require('express');
var app = express();
app.set('view engine','ejs');
app.get('/addbook',router.addbook);
app.get('/doadd',router.doadd);
app.get('/edit',router.edit);
app.listen(3000);
//book.js
var mongoose = require('mongoose');
var db = require('./db.js');
var ObjectId = require('mongodb').ObjectId();
var bookSchema = new mongoose.Schema({
name:{type:String},
autor:{type:String},
price:{type:Number},
type:{type:Array}
});
bookSchema.statics.liechusuoyoushu = function(callback){
this.model('Book').find({},callback);
}
bookSchema.statics.findBookById = function(id,callback){
this.model('Book').find({'_id':new ObjectId(id)},callback);
}
var bookModel = db.model('Book',bookSchema);
module.exports = bookModel;
var Book = require('../models/Book.js');
exports.showIndex = function(req,res,next){
Book.liechusuoyoushu(function(err,result){
res.render('index',{
'tushu' : result
});
});
}
export.addbook = function(req,res,next){
res.render('addbook');
}
exports.doadd = function(req,res,next){
Book.create(req.query,function(err){
if(err){
res.send('失败');
}
res.send('保存成功');
})
}
exports.edit = function(req,res,next){
Book.findBookById(req.query.id,function(err,result){
res.render('edit',result[0]);
});
}
exports.doedit = function(req,res,next){
Book.update(req.query.name,function(err,result){
res.render('edit',result[0]);
})
}
网友评论