接之前的实现留言板功能
- 定义留言板数据的Schema,在model.js中:
// 定义Comment schema
const CommentSchema = mongoose.Schema({
content: {
type: String,
required: true
},
username:String // 用户名
}, {timestamps: true})
- 定义comment model
// 定义comment model
const Comment = mongoose.model('comment', CommentSchema)
- 导出model
module.exports = {
Comment
}
- 在路由文件中引入comment model (comments.js中)(改造创建接口)
const {Comment} = require('../db/model');
// 定义路由:模拟创建留言
router.post('/create', async(ctx) => {
const body = ctx.request.body // 获取request body
console.log('body', body)
// 获取数据
const {content, username} = body;
// 插入数据库
const newComment = await Comment.create({
content,
username
})
ctx.body = {
errorno:0,
message: '成功',
date: newComment
}
})
-
运行‘
npm run dev
’ 启动服务,测试接口
a. 打开postman,调create接口
以上新增了一条数据,到compass中查看
-
改造查询接口
// 定义路由,模拟获取留言版列表,ctx是res和req的集合
router.get('/list', async(ctx) => { // router地址为 /api/list
const query = ctx.query // 获取req,即querystring
// 获取数据库的列表
const commentList = await Comment.find().sort({_id: -1});
ctx.body = {
errorno: 0,
data: commentList
} // 返回的内容即res
console.log('query', query);
})
访问查询接口,获取数据
完整代码:
app.js
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users')
const comments = require('./routes/conmments.js')
// error handler 错误处理器
onerror(app)
// middlewares 中间件 (app.use(...))
app.use(bodyparser({ // request body的转换
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger()) // 日志格式化
app.use(require('koa-static')(__dirname + '/public')) // 静态文件服务
app.use(views(__dirname + '/views', { // 服务端模版引擎
extension: 'pug'
}))
// logger 打印当前请求所花费的时间
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// 模拟登陆,为了使用中间件
// app.use(async(ctx, next) => {
// // next为下一个中间件,此处下一个中间件为路由
// const query = ctx.query;
// if (query.user === '张三') {
// // 模拟登陆成功
// await next(); // 执行下一步中间件
// }else {
// // 模拟登陆失败
// ctx.body = '请登录'
// }
// })
// routes 注册路由
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(comments.routes(), comments.allowedMethods()); // allowedMethods()对于404或返回是空的情况的一种补充
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
module.exports = app
db.js中
// 连接数据库(mongodb的服务端)
// 获取mongoose插件
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017';
const dbName = 'comment2'
// 连接数据库
mongoose.connect(`${url}/${dbName}`, {
useNewUrlParser: true,
useUnifiedTopology: true
});
// 获取当前的连接对象
const conn = mongoose.connection;
// 监听错误
conn.on('error', err => {
console.error('mongoose连接出错', err)
})
module.exports = mongoose;
model.js中
// 数据模型(规范数据格式)
const mongoose = require('./db')
// 定义User schema(数据规范)
const UserSchema = mongoose.Schema({
username: {
type: String,
required: true, // 必填
unique: true // 唯一,不重复
},
password: String,
age: Number,
city: String,
gender: {
type: Number,
default: 0 // 设置默认值,0-保密,1-男,2-女
}
}, {
timestamps: true // 时间戳,自动添加文档的创建时间
})
// 定义User Model
const User = mongoose.model('user', UserSchema)
// 定义Comment schema
const CommentSchema = mongoose.Schema({
content: {
type: String,
required: true
},
username:String // 用户名
}, {timestamps: true})
// 定义comment model
const Comment = mongoose.model('comment', CommentSchema)
module.exports = {
User,
Comment
}
comment.js中
const router = require('koa-router')();
router.prefix('/api'); // 前缀
const {Comment} = require('../db/model');
// 定义路由,模拟获取留言版列表,ctx是res和req的集合
router.get('/list', async(ctx) => { // router地址为 /api/list
const query = ctx.query // 获取req,即querystring
// 获取数据库的列表
const commentList = await Comment.find().sort({_id: -1});
ctx.body = {
errorno: 0,
data: commentList
} // 返回的内容即res
console.log('query', query);
})
// 定义路由:模拟创建留言
router.post('/create', async(ctx) => {
const body = ctx.request.body // 获取request body
console.log('body', body)
// 获取数据
const {content, username} = body;
// 插入数据库
const newComment = await Comment.create({
content,
username
})
ctx.body = {
errorno:0,
message: '成功',
data: newComment
}
})
// 输出
module.exports = router;