上一週學了下mongoose,雖然學了點皮毛,但仍是想寫寫總結總結,這也是個人第一篇技術博客。仍是蠻開心的,happy~~來,切入正題!項目源碼我會放在github上。 github 地址html
有些東西可根據本身喜愛設置,並不是必須。前端
$ mkdir student_manage
$ cd student_manage
$ npm init複製代碼
1.1 Express 基於 Node.js 平臺,快速、開放、極簡的 web 開發框架。
Express 4.x API 中文手冊 安裝以下:node
$ npm install express --save複製代碼
1.2 body-parser用於解析客戶端請求的body中的內容,內部使用JSON編碼處理,url編碼處理以及對於文件的上傳處理。安裝以下:jquery
$ npm install body-parser --save複製代碼
2.1 mongoose是在node.js異步環境下對mongodb進行便捷操做的對象模型工具。
mongoose文檔 安裝以下:git
$ npm install mongoose --save複製代碼
固然在項目開始前要肯定電腦是否安裝mongoDB github
mongoDB下載地址
mongoDB圖形化界面robomongoweb
下載好具體怎麼配置還請問度娘或Google吧,本文不作介紹了哈。注意:安裝完mongoDB的時候進行項目時要把lib目錄下的mongod服務器打開哈~~ajax
先展現下最終實現的項目效果,以防你們內心有數。mongodb
前臺具體代碼就不列出來,比較簡單,爲了節約時間,就使用bootstrap進行快速生成,固然你們能夠進行美化。數據庫
//引入mongoose模塊
var mongoose=require('mongoose')
//數據庫鏈接地址 連接到myStudent數據庫
var DB_URL='mongodb://localhost:27017/myStudent'
//數據庫鏈接
mongoose.connect(DB_URL)
//鏈接成功終端顯示消息
mongoose.connection.on('connected',function () {
console.log('mongoose connection open to '+DB_URL)
})
//鏈接失敗終端顯示消息
mongoose.connection.on('error',function () {
console.log('mongoose error ')
})
//鏈接斷開終端顯示消息
mongoose.connection.on('disconnected',function () {
console.log('mongoose disconnected')
})
//建立一個Schema 每個schema會一一對應mongo中的collection
var schema=mongoose.Schema
//實例化一個Schema
var studentSchema=new schema(
{
//設置studentSchema信息的數據格式
name:{type:String},
sex:{type:String},
age:{type:Number},
phone:{type:String},
email:{type:String},
other:{type:String},
},
//{versionKey: false}是幹嗎用?若是不加這個設置,咱們經過mongoose第一次建立某個集合時,
// 它會給這個集合設定一個versionKey屬性值,咱們不須要,因此不讓它顯示
{
versionKey:false
}
)
//生成一個具體student的model並導出
//第一個參數是集合名,在數據庫中會自動加s
//把Model名字字母所有變小寫和在後面加複數s
var student=mongoose.model('student',studentSchema)
//將Student的model導出
module.exports=student複製代碼
裏面的代碼我已逐條進行註釋。有幾個要說明的地方:1.可能你們看到Schema的時候有一點懵,不過他理解起來挺簡單的就像關係型數據庫裏面的表。定義能夠這麼講:schema是mongoose裏會用到的一種數據模式,能夠理解爲表結構的定義;每一個schema會映射到mongodb中的一個collection,它不具有操做數據庫的能力。2.生成一個student的model的時候,若是myStudent數據庫裏面沒有student(第一個參數的值)集合的話,系統會自動建立一個students的collection,注意在student後面加了s。
//調用函數, express實例化
var app=expres()
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
//處理靜態目錄
app.use(expres.static('www'))
// 容許跨域訪問///
app.all('/api/', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '')
res.header('Access-Control-Allow-Headers', 'x-Request-with')
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
res.header('X-Powered-By', '4.15.2')
res.header('Content-Type', 'application/json;charset=utf-8')
next() //執行下一個中間件。
})
//首頁展現獲取數據
app.post('/index',function (req,res) {
//mongoose 數據查找
student.find({}).exec(function (error,data) {
if (error){
console.log('數據獲取失敗'+error)
}
else{
res.json({
status:'y',
message:'查詢成功',
//傳遞返回的數據
data:data
})
}
})
})
//修改頁面 獲取數據
app.post('/modify',function (req,res) {
//mongoose根據條件進行查找
student.find({_id: req.body.id}).exec(function (error,data) {
console.log('2')
if (error){
console.log('數據獲取失敗'+error)
}
else{
console.log(data)
res.json({
status:'y',
message:'查詢成功',
data:data
})
console.log(4)
}
})
})
//修改提交修改數據庫
app.post('/modifyStu',function (req,res) {
console.log('1')
console.log(req.body)
//查詢的條件
var whereStr={_id:req.body.id}
//更新的內容
var updateStr={
$set:{
name:req.body.name,
sex:req.body.sex,
age: req.body.age,
phone:req.body.phone,
email:req.body.email,
other:req.body.other,
}
}
//對數據庫進行更新
student.update(whereStr,updateStr,function (error) {
if (error){
console.log('數據修改失敗:'+error)
res.json({
status:'y',
message:'修改失敗',
data:req.body
})
}
else{
console.log('數據修改爲功')
res.json({
status:'y',
message:'修改爲功',
data:req.body
})
}
})複製代碼
})
//刪除數據庫其中的項
app.post('/del',function (req,res) {
//mongoose根據指定條件進行刪除
student.remove({_id: req.body.id},function(error){
if (error){
console.log('數據獲取失敗'+error)
res.json({
status:'y',
message:'刪除不成功',
})
}
else{
res.json({
status:'y',
message:'刪除成功',
})
}
})
})
//導航欄search操做
app.post('/findName',function (req,res) {
console.log(req.body.searchName)
student.find({name: req.body.searchName}).exec(function (error,data) {
if (error){
console.log('查詢失敗'+error)
res.json({
status:'y',
message:'查詢失敗',
})
}
else{
res.json({
status:'y',
message:'查詢成功',
data:data
})
}
})
})
//添加數據庫操做
app.post('/addStu',function (req,res) {
console.log(req.body)
//實例化一個student
var newStu=new student({
name:req.body.name,
sex:req.body.sex,
age:req.body.age,
phone:req.body.phone,
email:req.body.email,
other:req.body.other,
})
//對實例化的內容進行保存
newStu.save(function (error) {
if (error){
console.log('數據添加失敗:'+error)
res.json({
status:'y',
message:'添加失敗',
data:req.body
})
}
else {
console.log('數據添加成功')
res.json({
status:'y',
message:'添加成功',
data:req.body
})
}
})複製代碼
})
//服務器監聽端口
app.listen(3000,()=>{
console.log('node is ok')
})
處處服務器搭建完成,接下來就是對各個js代碼進行操做,ajax獲取表單數據請求服務器,ajax獲取地址欄請求服務器等等。而後ajax在接收到服務器返回的數據,對此進行渲染到前臺頁面,此項目我用的是 **artTemplate** 進行模板渲染。
就舉一個栗子吧~~
3. 添加頁的 addAjax.js
``` bash
$(function () {
//添加表單驗證方法 手機號的驗證
$.validator.addMethod('isPhone',function (value,ele) {
var length=value.length
var reg=/^1[34578]\d{9}$/
if (length >= 11 && reg.test(value)){
return true
}
else {
return false
}
})
//對錶單進行驗證
$('#addForm').validate({
debug:true,
//驗證的規則
rules:{
name:{
required:true,
minlength:3
},
age:{
required:true
},
phone:{
required:true,
isPhone:true
},
email:{
required:true,
email:true
}
},
//錯誤的提示信息
messages:{
name:{
required:'姓名不能爲空',
minlength:'姓名不能少於3位'
},
age:{
required:'年齡不能爲空'
},
phone:{
required:'手機號不能爲空',
isPhone:'手機號格式錯誤'
},
email:{
required:'郵箱不能爲空',
email:'郵箱格式錯誤'
}
},
//正確時執行的函數
submitHandler:function (form) {
//ajax請求
$.ajax({
type:'post',
url:'/addStu',
dataType:'json',
//表單數據序列化
data:$(form).serialize(),
//ajax請求成功操做
success:function (res) {
$('.modal-body').text(res.message)
//顯示出模態框
$('.modal').modal('show').on('hidden.bs.modal',function () {
if (res.message == '添加成功'){
location.href='index.html'
}
})
},
//ajax請求失敗操做
error:function (jqXHR) {
console.log(jqXHR.status)
}
})
},
})
})複製代碼
表單驗證我用了 jquery.validate.js
添加完畢,首頁進行渲染 index.html(部分)
{{each}}
<tr>
<td>{{$value.name}}</td>
<td>{{$value.sex}}</td>
<td>{{$value.age}}</td>
<td>{{$value.phone}}</td>
<td>{{$value.email}}</td>
<td>
<a href="/modify.html?id={{$value._id}}" class="modify" data-index="{{$value._id}}">修改</a>
<a href="" class="del" data-index="{{$value._id}}">刪除</a>
</td>
</tr>
{{/each}}複製代碼
首頁的 indexAjax.js(部分)
$(function () {
$.ajax({
type:'post',
url:'/index',
success:function (res) {
//進行模板渲染
var strHtml=template('showStu',res.data)
$('#tb').html(strHtml)
......代碼有點長就不放了哈~~........複製代碼
夜已深。不知不覺寫這個文章也花了挺長時間的,哈哈哈,不過本身開心就行~~ 本身在作這個項目的時候,覺得會很快搞完,可是仍是遇到了問題,哎,糾結了很久,如今也沒得出個答案,後來用了另外一種的解決方法,感受有點像投機取巧,但好像也不能怎麼說,哈哈...我的技術水平真的很渣,寫文章一方面是分享,一方面是再次重溫本身的思路。請勿噴哈~~本身的第一篇技術博客,寫的有點匆忙,不過仍是但願能夠給你們帶來幫助。
於 廈門高崎新村 本身的小屋
本文首發於我的博客 >> 黃明照--一個在路上慢慢行走的前端人