1.models

  1. //1 models/baseDB/db-movie.js
  2. const mongoose = require("mongoose");
  3. /* 1.连接本地数据库 */
  4. var mongodb = mongoose.createConnection('mongodb://127.0.0.1:27017/movies', {
  5. useNewUrlParser: true,
  6. useUnifiedTopology:true
  7. });
  8. var Schema = mongoose.Schema;
  9. module.exports = {
  10. mongodb,
  11. Schema
  12. };
  1. //2 models/Schama/MovieSchema.js
  2. module.exports = {
  3. pic:String,
  4. title:String,
  5. rating:String,
  6. slogo:String,
  7. evaluate:String,
  8. labels:Array,
  9. collected:Boolean
  10. }
  1. //3 models/movie.js
  2. const {mongodb,Schema} = require("./baseDB/db-movie");
  3. const bean = require("./Schema/MovieSchema");
  4. const MovieSchema = new Schema(bean)
  5. function MovieModel(table){
  6. return mongodb.model(table,MovieSchema,table);
  7. }
  8. module.exports = MovieModel;

2.routers

  1. //1 routers/api/movie.js
  2. const router = require("koa-router")();
  3. const MovieModel = require("../../models/movie");
  4. router.get("/api/movie",async ctx=>{
  5. const {m} = ctx.query;
  6. try {
  7. var data = await MovieModel(m).find({});
  8. if(data.length){
  9. ctx.body = {
  10. code:200,
  11. res:data,
  12. msg:m
  13. }
  14. }else{
  15. throw new Error("输入字段不合法");
  16. }
  17. }catch(err){
  18. ctx.body = {
  19. code:400,
  20. msg:"输入字段不合法"
  21. }
  22. }
  23. })
  24. module.exports = router;