Node 实现增删改查
首先 app.js 中
app.use(koaBody({
strict:false
})); 为了可以删除任意一个id
// 引入类 const Koa = require('koa'); const Router = require('koa-router'); const koaBody= require('koa-body') const tagRouter=require("./routers/tag.router"); const userRouter=require("./routers/user.router"); const contentRouter=require("./routers/content.router"); // 引入内部方法或属性 // coust{方法或属性名} =require('koa'); // 创建对象 const app = new Koa(); app.use(koaBody({ strict:false })); const router=new Router(); //创建路由,支持传递参数 tagRouter(router); userRouter(router); contentRouter(router); app.use(router.routes()); app.use(router.allowedMethods({ // throw: true, // 抛出错误,代替设置响应头状态 // notImplemented: () => '不支持当前请求所需要的功能', // methodNotAllowed: () => '不支持的请求方式' })); // localhost:3000 app.listen(3000,()=>{ console.log("http://localhost:3000") });
然后 mongodb.js
const mongoose=require("mongoose"); //导入
mongoose.connect("mongodb://127.0.0.1:27017/test")
const tagSchema= new mongoose.Schema({ //创建一个模型 对数据进行约束
// text: String,
text:{
type:String,
minlength:2,
maxlength:12
}
})
const contentSchema= new mongoose.Schema({ //创建一个模型 对数据进行约束
title:{
type:String,
minlength:6,
maxlength:12
},
content:{
type:String,
minlength:10,
maxlength:50
},
top:{
type:Boolean,
default:false //默认不置顶
}
})
const userSchema= new mongoose.Schema({ //创建一个模型 对数据进行约束
username:{
type:String,
minlength:2,
maxlength:[12,"用户名最多12个字符"]
},
password:{
type:String,
validate: { //对他验证
validator: function(v) {
return /[a-zA-Z0-9_]{6,12}/.test(v); //验证器
},
message: "密码只能是6-12位的数字、字母和下划线的任意组合"
},
},
Email:{
type:String,
validate: { //对他验证
validator: function(v) {
return /\w+@\w+\.\w+/.test(v); //验证器
},
message: "邮箱格式不正确"
},
},
group:{
type:String,
enum:{
values: ['限制会员','新手上路','组册会员','中级会员','高级会员'], //枚举
message: '{VALUE} is not supported'
}
}
})
const tagModel=new mongoose.model("tag",tagSchema); //生成model,实现增删改查
const contentModel=new mongoose.model("content",contentSchema);
const userModel=new mongoose.model("user",userSchema);
// tagModel.
module.exports= {tagModel,contentModel,userModel}
然后 tag.router.js , content.router.js user.router.js
// 添加 删除 const {tagModel}=require("../mongodb"); //引入 const {success,fail}=require("../toast") module.exports=function (router){ //导出 //查询 router.get("/tag",async (ctx)=>{ try{ const data= await tagModel.find({}); return success(ctx,data); }catch(error){ return fail(ctx,error) } }) //添加 router.post("/tag",async ctx=>{ try{ const data= await tagModel.create(ctx.request.body); return success(ctx,data); }catch(error){ return fail(ctx,error) } }) //删除 router.delete("/tag",async ctx=>{ try{ const data= await tagModel.deleteOne(ctx.request.body); return success(ctx,data); }catch(error){ return fail(ctx,error) } }) }
content.router.js
const {contentModel}=require("../mongodb"); //引入
const {success,fail}=require("../toast")
module.exports=function(router){
router.get("/content", async ctx=>{
try{
const data= await contentModel.find({});
return success(ctx,data);
}catch(error){
return fail(ctx,error)
}
})
//添加
router.post("/content",async ctx=>{
try{
const data= await contentModel.create(ctx.request.body);
return success(ctx,data);
}catch(error){
return fail(ctx,error)
}
})
//删除
router.delete("/content",async ctx=>{
try{
const data= await contentModel.deleteOne(ctx.request.body);
return success(ctx,data);
}catch(error){
return fail(ctx,error)
}
})
//更改
router.put("/content",async ctx=>{
try{
const data= await contentModel.updateOne(ctx.query,ctx.request.body);
return success(ctx,data);
}catch(error){
return fail(ctx,error)
}
})
}
再 toast.js 中 success,fail 与 tag.router.js 中 {success,fail} 相对应
module.exports={ success:function(ctx,data=null){ ctx.body={ status:200, data:data, msg:"" } }, fail:function(ctx,msg){ ctx.body={ status:0, data:null, msg:msg.message||msg } } }
再 test.http ,用Send Request 查看结果
###查询 GET http://localhost:3000/tag ###添加 POST http://localhost:3000/tag Content-Type: application/json { "text":"HTml" } ###删除 DELETE http://localhost:3000/tag HTTP/1.1 Content-Type: application/json { "_id": "61a5c8b9b793e9ed045e57c2" }
再 test.http(第二种方法) ,用Send Request 查看结果
@url=http://localhost:3000 @json=Content-Type: application/json ###查询 GET {{url}}/tag ###添加 POST {{url}}/tag {{json}} #content //表单方式 #id=1000&name="张三" { "text":"HTml" } ###删除 DELETE http://localhost:3000/tag Content-Type: application/json { "_id": "61a5c8b9b793e9ed045e57c2" } ###查询 GET http://localhost:3000/content ###删除 DELETE http://localhost:3000/content Content-Type: application/json { "_id": "61a5c8b9b793e9ed045e57c2" } ###查询 GET http://localhost:3000/user ###添加 POST http://localhost:3000/user Content-Type: application/json #content { "username":"莹萍", "password":"123456 ", "Email":"2178625574@qq.com", "group":"限制会员" } ###查询内容 GET {{url}}/content ###添加内容 POST {{url}}/content {{json}} { "title":"标dhudh题", "content":"fshduovhodf " } ###修改内容 PUT {{url}}/content?_id=61a8848be4a6f108177fa8de {{json}} { "top":true }
content.router.js user.router.js 同理

浙公网安备 33010602011771号