Express+MongoDB

express 的使用

1
2
#安装 express
npm install --save express
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const express = require('express');
const app = express();

//第一个参数是路径
app.get('/',function(req,res){
res.send('Hello world')
})
// 大多数情况返回给前台的是JSON数据
app.get('/data',function(req,res){
res.json({name:'Beme',age:'22'})
})

app.listen(3000,function(){
console.log("ok")
})
  • app.get、app.post分别开发get和post接口
  • app.use使用模块
  • res.send、res.json、ressendFile响应不同的内容

MongoDB

1
npm install --save mongoose
1
2
3
4
5
6
7
//连接数据库,并且使用ceshi这个集合,没有的话会自动新建
const mongoose = require('mongoose');
const DB_URL = 'mongodb://localhost:27017/ceshi';
mongoose.connect(DB_URL);
mongoose.connection.on('connected',function(){
console.log('mongo connected')
})

mongoose使用

  • connect连接数据库
  • 定义文档类型,schema和model新建模型
  • 一个数据库文档对应一个模型,通过模型对数据库进行操作
1
2
3
4
5
//类似于MySQL的表,mongo里有文档、字段的概念
const User = mongoose.model('user',new mongoose.Schema({
user:{type:String,require:true},
age:{type:Number,require:true}
}))

mongoose文档

  • String、Number等数据结构
  • create、remove、update用来增、删、改的操作
  • find和findOne用来查数据

1
2
3
4
5
6
7
8
9
10
11
//create新增数据
User.create({
user:'Beme',
age:22
},function(err,doc){
if (!err) {
console.log(doc)
}else {
console.log(err)
}
})
1
2
3
4
//删除数据
User.remove({age:20},function(err,doc){
console.log(doc)
})
1
2
3
4
//更新数据,user:过滤条件
User.update({'user':'Beme'},{'$set':{age:18}},function(err,doc){
console.log(doc)
})

后续进阶

  • mongodb独立工具函数
  • express使用body-parser支持post函数
  • 使用cookie-parser存储登录信息cookie
------ 本文结束 ------
0%