koa2写查询接口, 通过 number 参数可以设置返回的条数

48 阅读1分钟

接着上一篇post接口,这一篇在原来的基础上写get接口

每一次改动代码,都要重启服务 npm run start

最终效果如下

1.png

完整的代码如下

const router = require("koa-router")();
const { Comment } = require("../db/comment");
router.prefix("/comment");
// 创建留言的接口
router.post("/create", async (ctx, next) => {
	const body = ctx.request.body;
	// 获取留言内容和留言者的姓名
	const { content, username } = body;
	// 把数据添加到数据库
	const newComment = await Comment.create({
		content,
		username,
	});
// 返回信息给前端
	ctx.body = {
		errno: 0,
		message: "新增留言成功!",
		data: newComment,
	};
});

// get获取留言列表
router.get("/list",async (ctx,next)=>{
    // 获取queryString
    const queryNumber = ctx.query.number || 5;
// 查询数据库,按照创建时间倒序,并且要搜索指定的条数
const commentList = await Comment.find().sort({createdAt:-1}).limit(queryNumber)
// 返回json
ctx.body = {
    errno:0,
    data:commentList,
}
})


# 接着上一篇post接口,这一篇在原来的基础上写get接口

// 获取留言的接口
router.get("/list", async (ctx, next) => {});
module.exports = router;