models:
const mongoose = require("mongoose");
//1.连接本地数据库
var mongodb = mongoose.createConnection( 'mongodb://127.0.0.1:27017/movies', {useNewUrlParser: true});
var Schema = mongoose.Schema;
module.exports = {
mongodb,
Schema
};
const {mongodb,Schema} = require("./baseDB/db-movies");
//2.在本地定义一个Schema和远程数据库的字段映射
var MovieSchema =new Schema({
pic:String,
title:String,
raiting:String,
slogo:String,
evaluate:String,
labels:Array
});
// 3.创建数据模型,操作数据库 table是需要访问的集合名
function MovieModel(table){
return mongodb.model(table,MovieSchema,table); //是我们获取的数据库里叫table(变量)的那张表
}
module.exports = MovieModel;
在路由中使用:
const router = require("koa-router")();
const MovieModel = require("../../models/movie");
router.get("/api/movie",async ctx=>{
let {m} = ctx.query;
var data = await MovieModel(m).find().sort({rating:-1});
ctx.body = {
code:200,
res:data,
request:"GET /api/top250"
}
})
module.exports = router;