app.js
const express = require('express')
const app = express()
const router =require('./router')
const bodyparser = require('body-parser')
app.use(router)
app.use(bodyparser.urlencoded({extended:false}))
app.use(bodyparser.json())
app.get('/',function (req,res){
res.send('hello world')
})
app.use(function (req,res,next){
res.send('您找的页面不存在')
})
app.listen(3000,function (){
console.log('the server is running at port 3000......')
})
router.js
const express = require('express')
const student =require('./connect')
const router = express.Router()
const bodyparser = require('body-parser')
router.use(bodyparser.urlencoded({extended:false}))
router.use(bodyparser.json())
router.get('/get',function (req,res){
res.send('router get')
})
//全部查找
router.get('/all',(req,res)=>{
student.find(function (err,data){
if(err){
console.log(err)
}else{
console.log(data)
res.send(data)
}
})
})
//增添数据
router.post('/save',(req,res)=>{
console.log(req.body)
new student({name:req.body.name,phone:req.body.phone}).save(function (err){
if(err){
console.log(err)
res.send('Save False')
}else {
res.send('Save Success')
console.log('Save Success!')
}
})
})
//删除数据
router.post('/del',(req,res)=>{
student.deleteOne({name:req.body.name},function (err){
if(err){
console.log(err)
res.send('Remove Success')
}else{
console.log('remove Success')
res.send('Remove Success')
}
})
})
//更新数据库
router.post('/update',(req,res)=>{
student.update({name:req.body.name},{$set:{phone:req.body.phone}},function (err){
if(err){
console.log(err)
res.send('Update false')
} else{
console.log('Update Success')
res.send('Update Success')
}
})
})
module.exports=router
connect.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')
.then(()=>console.log('连接数据库成功'))
.catch(err=>console.log(err,'连接数据库失败……'))
const stu =new mongoose.Schema({
name:String,
phone:Number
})
module.exports = mongoose.model('Student',stu);
网友评论