一、创建文章的Model
var mongoose = require('mongoose')
const baseModel = require('./base-model.js')
const Schema = mongoose.Schemaconst 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.queryconst 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
修正上图存在的错误:
七、删除文章