egg + mongoose RESTful api设计实例

安装egg mongoose

npm init egg --type=simple
npm i 
npm init egg-mongoose 
npm run dev

配置mongoose

/config/plugin.js
  mogoose: {
    enable: true,
    package: 'egg-mongoose',
  }
/config/config.default.js
  config.mongoose = {
    url: 'mongodb://localhost:27017/test',
    option: {
      server: {
        poolSize: 40,
      },
    },
  }

设计文章管理系统

  • 定义一个文章的数据模型
    app/model/articles.js
'use strict';
module.exports = app => {
    const mongoose = app.mongoose;
    const Schema = mongoose.Schema;
    const articlesSchema = new Schema({
        title: {
            type: String,
        },
        description: {
            type: String,
        },
        body: {
            type: String,
        },
        tagList: {
            type: Object,
        },

    });
    // 第一个参数 模型名称,第二个参数模型,第三个参数数据库对应集合
    return mongoose.model('articles', articlesSchema,'articles');
}
  • 创建文章
    创建文章需要提交数据所以:POST / articles
    app/router.js 添加路由
router.post('/articles', controller.articles.create);

app/controller/articles.js
1.获取客户端表单数据
2.数据验证
3.把验证成功的数据插入数据库,失败的数据返回失败原因加状态码。

文章不符合要求,不进行创建并返回失败原因+状态码:422
文章符合要求,进行创建,返回数据库创建好的文件并加上状态码:201

    async create() {
        const body = this.ctx.request.body;
        const { article } = body;
        // 验证文章 标题 描述是否存在 ,不存在直接返回false
        if (!article || !article.title || !article.description) {
            this.ctx.status = 422;
            return this.ctx.body = { error: "文章不符合要求" };
        } else {
            const result = await this.ctx.service.articles.create(article);
            this.ctx.status = 201;
            this.ctx.body = { article: result };
        }

    }

app/service/articles.js
进行创建
重点:this.ctx.model.模型, 这里的模型必须是大写,创建的模型,写的是小写,但是用的时候开头必须要大写

    async create(article){
        const result = await this.ctx.model.Articles.create(article);
        return result;
    }

进行提交创建文章,使用postman示例:
在这里插入图片描述

  • 查询文章
    查询文章,GET/articles
    请求参数(Query)
    _size:每页数据量
    _page:第几页
    app/router.js
 router.get('/articles', controller.articles.get);

app/controller/articles.js

    async get() {
        const query = this.ctx.request.query;
        const result = await this.ctx.service.articles.get(query);
        this.ctx.body = result;
    }

app/service/articles.js
语法:skip 跳过多少条; limit 返回限制条数
重点:传过来query参数里面的数字是字符串格式需要自己转换成数字

    async get(query) {
        // 进行分页
        const { _page = 1, _size = 2 } = query;
        // 字符串转换成数字
        const page = +_page;
        const size = +_size;
        const skipNumber = (page - 1) * size;
        const limitNumber = size;
        console.log('skipNumber:', skipNumber);
        console.log('limitNumber:', limitNumber);
        const result = await this.ctx.model.Articles
            .find()
            .skip(skipNumber)
            .limit(limitNumber);
        return { articles: result, articlescount: await this.ctx.model.Articles.countDocuments() };
    }

postman请求示例:
在这里插入图片描述

  • 修改数据
    PUT / articles:id // 根据id修改数据
    app/router.js
  router.put('/articles/:id', controller.articles.put);

app/controller/articles.js

    async put() {
        const params = this.ctx.params;
        const body = this.ctx.request.body;
        const result = await this.ctx.service.articles.put(params.id, body.article);
        this.ctx.status = 201;
        this.ctx.body = result;
    }

app/service/articles.js

    async put(_id, article) {
        const result = await this.ctx.model.Articles.updateOne({ _id }, article);
        return result;
    }

postman示例:
在这里插入图片描述

  • 删除数据
    DELETE / articles:id 根据id删除数据
    app/router.js
router.delete('/articles/:id', controller.articles.delete);

app/controller/articles.js
重点:204 ,服务器处理成功,但返回无内容

    async delete(){
        const params = this.ctx.params;
        const result = await this.ctx.service.articles.delete(params.id);
        this.ctx.status = 204;
        this.ctx.body = result;
    }

app/service/articles.js

    async delete(_id){
        const result = await this.ctx.model.Articles.deleteOne({_id});
        return result;
    }

postman 示例:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值