如何实现多个路由器引用1个mongodb的模块(或者骨架)?
简单代码例子:
路由:
router.get('/', async (ctx, next)=> {
await ctx.render('index',{})
}
);
router.get('/about', async (ctx, next)=>{
await ctx.render('about',{})
},
router.get('/content', async (ctx, next)=> {
await ctx.render('content',{})
},
mongodb查询一个集合:
let mongoose = require('mongoose');
let conSchema = mongoose.Schema({
title:{type:String},
info:{type:String},
keywords:{type:String},
description:{type:String}
});
let conscModel = mongoose.model('cons',conSchema);
把查询写在路由上:
let mongoose = require('mongoose');
let conSchema = mongoose.Schema({
title:{type:String},
info:{type:String},
keywords:{type:String},
description:{type:String}
});
let conscModel = mongoose.model('cons',conSchema);
conscModel .find({},function(err,data) {data});
router.get('/', async (ctx, next)=> {
await ctx.render('index',{})
});
router.get('/about', async (ctx, next)=>{
await ctx.render('about',{})
});
router.get('/content', async (ctx, next)=> {
await ctx.render('content',{})
});
如何实现都加载?这个方法1是不行:
let conscModel = mongoose.model('cons',conSchema);
let conn = conscModel .find({},function(err,data) {data});
router.get('/', async (ctx, next)=> {
await ctx.render('index',{ web:conn })
});
router.get('/about', async (ctx, next)=>{
await ctx.render('about',{ web:conn})
});
router.get('/content', async (ctx, next)=> {
await ctx.render('content',{ web:conn})
});
这个方法2是不行能实现,但是 如果其他查询是没办法写了:
let conscModel = mongoose.model('cons',conSchema);
router.get('/', async (ctx, next)=> {
await conscModel .find({},function(err,data) {
ctx.render('index',{ web:conn })
}
}
});
router.get('/about', async (ctx, next)=>{
await conscModel .find({},function(err,data) {
ctx.render('about',{ web:conn })
}
}
});
router.get('/content', async (ctx, next)=> {
await conscModel .find({},function(err,data) {
ctx.render('content',{ web:conn })
}
}
});
有更好办法吗?或者更好的继承办法?
分层设计
路由和模型之间加一层控制器来处理业务逻辑
我之前看到的一个koa+mysql写的也可以参考下,原理类似
koa-blog