// 三张表
top250
comingSoon
inTheaters
models/baseDB/db-movies.js 连接数据库
const mongoose = require("mongoose")
var mongodb = mongoose.createConnection( 'mongodb://127.0.0.1:27017/movies', {
useNewUrlParser: true,
useUnifiedTopology:true
});
var Schema = mongoose.Schema
module.exports ={
mongodb,
Schema
}
models/Schema/MovieSchema.js 封装数据格式
module.exports={
pic:String,
title:String,
slogo:String,
evaluate:String,
labels:Array,
rating:String
}
models/movie.js 封装MovieModel
const {mongodb,Schema} = require("./baseDB/db-movies")
const bean = require("./Schema/MovieSchema")
const MovieSchema = new Schema(bean)
function MovieModel(table){
return mongodb.model(table,MovieSchema,table)
}
module.exports = MovieModel
routers/api/movie.js 前台API
const router = require("koa-router")()
const MovieModel = require("../../models/movie")
// /api/movie?m= top250 comingSoon inTheaters
router.get("/api/movie",async ctx=>{
var {m} = ctx.query
try{
var data = await MovieModel(m).find({}).sort({rating:-1})
if(data.length){
ctx.body={
code:200,
result:data,
msg:m
}
}else{
throw new Errow("输入的参数不合法")
}
}catch(err){
ctx.body={
code:400,
msg:"请求参数不合法"
}
}
})
module.exports = router