1. // 三张表
  2. top250
  3. comingSoon
  4. inTheaters

models/baseDB/db-movies.js 连接数据库

  1. const mongoose = require("mongoose")
  2. var mongodb = mongoose.createConnection( 'mongodb://127.0.0.1:27017/movies', {
  3. useNewUrlParser: true,
  4. useUnifiedTopology:true
  5. });
  6. var Schema = mongoose.Schema
  7. module.exports ={
  8. mongodb,
  9. Schema
  10. }

models/Schema/MovieSchema.js 封装数据格式

  1. module.exports={
  2. pic:String,
  3. title:String,
  4. slogo:String,
  5. evaluate:String,
  6. labels:Array,
  7. rating:String
  8. }

models/movie.js 封装MovieModel

  1. const {mongodb,Schema} = require("./baseDB/db-movies")
  2. const bean = require("./Schema/MovieSchema")
  3. const MovieSchema = new Schema(bean)
  4. function MovieModel(table){
  5. return mongodb.model(table,MovieSchema,table)
  6. }
  7. module.exports = MovieModel

routers/api/movie.js 前台API

  1. const router = require("koa-router")()
  2. const MovieModel = require("../../models/movie")
  3. // /api/movie?m= top250 comingSoon inTheaters
  4. router.get("/api/movie",async ctx=>{
  5. var {m} = ctx.query
  6. try{
  7. var data = await MovieModel(m).find({}).sort({rating:-1})
  8. if(data.length){
  9. ctx.body={
  10. code:200,
  11. result:data,
  12. msg:m
  13. }
  14. }else{
  15. throw new Errow("输入的参数不合法")
  16. }
  17. }catch(err){
  18. ctx.body={
  19. code:400,
  20. msg:"请求参数不合法"
  21. }
  22. }
  23. })
  24. module.exports = router