1.models
//1 models/baseDB/db-movie.js
const mongoose = require("mongoose");
/* 1.连接本地数据库 */
var mongodb = mongoose.createConnection('mongodb://127.0.0.1:27017/movies', {
useNewUrlParser: true,
useUnifiedTopology:true
});
var Schema = mongoose.Schema;
module.exports = {
mongodb,
Schema
};
//2 models/Schama/MovieSchema.js
module.exports = {
pic:String,
title:String,
rating:String,
slogo:String,
evaluate:String,
labels:Array,
collected:Boolean
}
//3 models/movie.js
const {mongodb,Schema} = require("./baseDB/db-movie");
const bean = require("./Schema/MovieSchema");
const MovieSchema = new Schema(bean)
function MovieModel(table){
return mongodb.model(table,MovieSchema,table);
}
module.exports = MovieModel;
2.routers
//1 routers/api/movie.js
const router = require("koa-router")();
const MovieModel = require("../../models/movie");
router.get("/api/movie",async ctx=>{
const {m} = ctx.query;
try {
var data = await MovieModel(m).find({});
if(data.length){
ctx.body = {
code:200,
res:data,
msg:m
}
}else{
throw new Error("输入字段不合法");
}
}catch(err){
ctx.body = {
code:400,
msg:"输入字段不合法"
}
}
})
module.exports = router;