①新建關於角色表的schema,model>role.js下新建role.js,鍵入以下代碼:javascript
module.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; var d = new Date(); const RoleSchema = new Schema({ title: { type: String }, description: { type: String }, status: { type: Number, default: 1 }, add_time: { type: Number, default: d.getTime() } }); return mongoose.model("Role", RoleSchema, "role"); };
②新建路由規則,新增角色提交表單會調用。java
router.post("/admin/role/doAdd", controller.admin.role.doAdd);
③增長角色的表單(增長隱藏域 csrf驗證)數據庫
<form action="/admin/role/doAdd" method="post"> <ul> <input type='hidden' name="_csrf" value="<%=csrf%>"></input> <li> 角色名稱: <input type="text" name="title"/></li> 角色描述:<textarea name="description" id="" cols="60" rows="8"></textarea> <li> <br/> <button type="submit" class="btn btn-default">提交</button> </li> </ul> </form>
④role controller打印post數據:app
async doAdd() { console.log(this.ctx.request.body); }
⑤增長角色表單,點提交async
⑥執行role下的doAdd controller的方法,打印post提交的數據mongoose
async doAdd() { console.log(this.ctx.request.body); }
⑥修改成以下邏輯:向數據庫中插入數據工具
async doAdd() { // console.log(this.ctx.request.body); let role = this.ctx.model.Role({ title: this.ctx.request.body.title, description: this.ctx.request.body.description }); let result = await role.save(); console.log(result); await this.success("/admin/role", "增長角色成功"); }
⑦如可視化工具可知,數據庫插入了一條數據:post
⑧改造角色列表頁面執行的controllerthis
async index() { let list = await this.ctx.model.Role.find({}); // console.log(list); await this.ctx.render("admin/role/index", { list }); }
⑨角色模板頁面的controller改造爲以下所示:spa
<table class="table table-bordered"> <thead> <tr class="th"> <th>角色名稱</th> <th>描述</th> <th>增長時間</th> <th>操做</th> </tr> </thead> <tbody> <%for(var i = 0;i<list.length;i++){%> <tr> <td><%=list[i].title%></td> <td><%=list[i].description%></td> <td><%=list[i].addTime%></td> <td class="text-center">修改 刪除</td> </tr> <%}%> </tbody> </table>
⑩添加角色成功後,便可讀出數據作頁面渲染:
十一、編輯功能 修改按鈕:訪問edit路由,執行controller的edit方法,傳一個id到下個頁面。
<td class="text-center"> <a href="/admin/role/edit?id=<%=list[i]._id%>">修改</a> </td>
十二、下個頁面根據這個id去查詢表單,作編輯回顯。
async edit() { let id = this.ctx.query.id; console.log(id); let list = await this.ctx.model.Role.find({ _id: id }); console.log(list); await this.ctx.render("admin/role/edit", { list }); }
1三、點提交要修改表單,則配置修改路由:
router.post("/admin/role/doEdit", controller.admin.role.doEdit);
1四、doEdit執行如下邏輯:查找對應id修改數據。
async doEdit() { let { _id, title, description } = this.ctx.request.body; let result = await this.ctx.model.Role.updateOne( { _id }, { title, description } ); console.log(result); if (result) { await this.success("/admin/role", "編輯角色成功"); } else { await this.error("/admin/role", "編輯角色失敗"); } }
15.
1六、刪除操做的話取一個id執行刪除操做就好了,明天說下封裝公共刪除方法。碎覺。