Express接口案例——完成文章增删改查接口

Posted 小小白学计算机

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Express接口案例——完成文章增删改查接口相关的知识,希望对你有一定的参考价值。

一、创建文章的Model



var mongoose = require('mongoose')
const baseModel = require('./base-model.js')
const Schema = mongoose.Schema

const articleSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    // 文章内容
    body: {
        type: String,
        required: true
    },
    // 文章标签
    tagList: {
        type: [String],
        default: null
    },
    // 点赞数量
    favoritesCount: {
        type: Number,
        default: 0
    },
    // 文章作者信息
    author: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    ...baseModel
})

module.exports = articleSchema

二、数据验证



三、完成创建文章接口


// 创建文章
exports.createArticle =  async (req, res, next) => {
    try {
        // 处理请求
        const article = new Article(req.body.article)
        await article.save()
        res.status(201).json({
            article: article
        })
    } catch (err) {
        next(err)
    }
}

创建成功返回结果为:

四、完成获取文章接口



五、查询文章列表


// 获取文章列表
exports.getArticles =  async (req, res, next) => {
    try {
        // 处理请求
        const { limit = 20, offset = 0, tag, author } = req.query
        const filter = {}
        if(tag) {
            filter.tagList = tag
        }
        if(author) {
            const user = await User.findOne({ username: author })
            filter.author = user ? user._id : null
        }
        const article = await Article.find(filter)
        .skip(Number.parseInt(offset)) // 跳过多少条
        .limit(Number.parseInt(limit)) // 取多少条
        .sort({
            // -1降序, 1 升序
            createdAt: -1
        })
        const articlesCount = await Article.countDocuments()
        res.status(200).json({
            article: article,
            articlesCount: articlesCount
        })
    } catch (err) {
        next(err)
    }
}

六、更新文章

6.1 封装验证ID是否有效的函数

https://express-validator.github.io/docs/check-api.html#buildcheckfunctionlocations


修正上图存在的错误:




七、删除文章



以上是关于Express接口案例——完成文章增删改查接口的主要内容,如果未能解决你的问题,请参考以下文章

node实现简单的增删改查接口

vue+express+mongodb 实现 增删改查

Express起步 - 路由基础 - 请求对象request - 响应对象response - 增删改查API案例

无需编程,基于PostgreSQL零代码生成CRUD增删改查RESTful API接口

使用DbUtils实现增删改查——ResultSetHandler 接口的实现类

基于React Hooks的增删改查(CRUD)实例