node模块的增删改查

tag模块

首先打开数据库链接

创建一个tag文件

 

 在mongodb.js里添加创建模型,对数据约束

const mongoose=require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/text")


// Schema创建模型,对数据约束
const tagSchema=new mongoose.Schema({
    // text:String,
    text:{
        type: String,
        minlength:2,
        maxlength:12
    }
});

const userSchema=new mongoose.Schema({
    // text:String,
    username:{
        type: String,
        minlength:2,
        maxlength:12
    }
});

const contentSchema=new mongoose.Schema({
    // text:String,
    title:{
        type: String,
        minlength:6,
        maxlength:12
    },
    content:{
        type: String,
        minlength:10,
        maxlength:50
    },
    top:{
        type: Boolean
    }
});


const tagModel=new mongoose.model("tag",tagSchema);
const userModel=new mongoose.model("user",userSchema);
const contentModel=new mongoose.model("content",contentSchema);
// tagModel 里面包括增删改查

module.exports={tagModel,userModel,contentModel};

// const arr=[{text:"html"},{text:"sql"},{text:"nodejs"}]
// tagModel.insertMany(arr,function(err,docs){
//     console.log(err);
//     console.log(docs);
// });
 
导入tag文件中
// 添加 删除
// 创建函数

const {tagModel}=require("../mongodb");
const {success,fail}=require("../toast");
/*
  get    ctx.query
  post   ctx.request.body
  delete ctx.request.body
  put    ctx.query ctx.request.body
*/

// module.exports=导出函数
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)
        }

    })
    //post添加
    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)
                 }
        })
   

}

// {
//     status :200,
//     data:{},
//     msg:""
// }
在text.http中添加数据

### 查询
GET http://localhost:3001/tag

###添加
POST http://localhost:3001/tag
Content-Type: application/json

#content
#id=1000&name=张三   表单方式
{
   
    "text":"张三"
}

###删除
DELETE http://localhost:3001/tag HTTP/1.1
Content-Type: application/json

{
     "_id": "61a5cf0722621a1cd89ff6f1"
}


 
posted @ 2021-12-01 13:40  嘎嘣脆儿  阅读(49)  评论(0)    收藏  举报