1.先使用脚手架, 搭建 koa2 项目, 然后添加 mongoose
win + r 打开cmd 切换到桌面,然后koa2 message-demo
使用npm i安装需要的包
使用npm run start启动服务
浏览器访问http://localhost:3000/
在nodejs里面安装mongoose npm i mongoose
2.在koa2项目根目录下新建db文件夹,在文件夹分别创建db.js,comment.js
在// db\db.js配置并链接数据库
代码如下
// db\db.js
// 数据库设置
const mongoose = require("mongoose");
const url = "mongodb://localhost:27017";
const dbName = "message-board";
// 开始连接
mongoose.connect(`${url}/${dbName}`);
const conn = mongoose.connection;
conn.on("error", (err) => console.log(err));
module.exports = mongoose;
定义数据结构db\comment.js
引入的时候,一定注意检查每一个路径是否有错
// db\comment.js
const mongoose = require("./db");
// 定义 Schema
const CommentSchema = mongoose.Schema(
{
content: {
type: String,
required: true,
},
username: {
type:String,
required:true,
},
},
{
timestamps: true,
}
);
const Comment = mongoose.model("comment", CommentSchema);
module.exports = {
Comment,
};
编写路由routes\comment.js
原来routes文件夹下的index.js user.js不要改动,模仿user.js编写comment.js即可
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,
};
});
// 获取留言的接口
router.get("/list", async (ctx, next) => {});
module.exports = router;
在路由下面编写好comment.js路由以后,开始在app.js中注册路由
模仿user.js的注册,复制多一个users,有users的地方,复制好以后,改成comment就可以了
使用 apipost 进行测试
一切可以正常执行
**查看 compass, 也会有对应的数据, **
程序会自动创建 collection, 命名方式是 comment 的复数, comments
这里不知道要不要和以前一样在MongoDB 下面的 C:\MongoDB\bin路径下使用cmd运行
mongod.exe --dbpath C:\MongoDB\date\db
我今天写的时候, 是用cmd执行了mongod.exe --dbpath C:\MongoDB\date\db开启了服务端
经过测试,post请求接口,可以访问,并且能返回新增的留言列表。