一、安装

  1. yarn add mongoose

二、导入mongoose

const mongoose = require('mongoose');
//1.连接数据库
mongoose.connect( 'mongodb://127.0.0.1:27017/student', {useNewUrlParser: true});
//2.定义Schema映射数据库中的表
var AdminSchema = new mongoose.Schema({
    name:String,
    age:Number
})
//3.创建模型,操作数据库
var Admin = mongoose.model('Admin',AdminSchema,'admin');
//4.查询
Admin.find({}).then(data=>{
    console.log(data)
})

三、拆分models

models/db.js

//models/db.js
const mongoose = require('mongoose');
mongoose.connect( 'mongodb://127.0.0.1:27017/student', {useNewUrlParser: true},(err)=>{
    if(err){throw err};
    console.log("数据库连接成功")
});
module.exports = mongoose;

models/admin.js

const mongoose = require('./db');
var AdminSchema =new mongoose.Schema({
    name:String,
    age:Number
})
var Admin = mongoose.model('Admin',AdminSchema,'admin');
module.exports = Admin;

四、跨域-路由

const router = new Router()
const path=require("path")
render(app, {
    root: path.join(__dirname, 'views'),
    extname: '.html', //后缀也可以写成.art
    debug: process.env.NODE_ENV !== 'production'
});
app.use(router.routes());
app.listen(8080)
yarn add koa2-cors
const cors = require("koa2-cors");
app.use(cors())

五、获取数据

const render = require("koa-art-template");
app.use(cors());
router.get('/admin/top',async ctx=>{
    var data=await AdminModel.find({});
    await ctx.render('index',{data})    //查找数据
})
router.get("/delete",async ctx=>{
    var {id}=ctx.query                  //先找到id
    console.log(ctx.query)
    await AdminModel.remove({_id:id})   //在删除数据
    ctx.redirect('/admin/top')          //重定向
})