当前位置: 首页 > 后端技术 > Node.js

【mongo】定义Schema,灵活创建读取mongo(零编码开发)(3-3)

时间:2023-04-03 19:16:50 Node.js

1.配置conf.jsmodule.exports={db:{url:'mongodb://127.0.0.1:27017/local',options:{useNewUrlParser:true,}}}2.入口index.jsconstKoa=require('koa');constapp=newKoa();constconfig=require('./conf')const{loadModel}=require('./framework/loader')//加载模型的配置对应字段loadModel(config)(app)//引入动态配置apiconstrest=require('./framework/router');//自动将传入的body字符串转换为对象值,cxt.request.bodyconstbodyParser=require('koa-bodyparser');app.use(bodyParser());应用程序使用(休息);常量端口=3000;app.listen(port,()=>{console.log('link3000');})3.定义Schema./model/user.jsmodule.exports={schema:{mobile:{type:String,required:true,},realName:{type:String,required:true,},}}4.加载定义好的Schema文件,读取配置到mongo./framework/loader.jsconstfs=require('fs');constpath=require('path');constmongoose=require('mongoose');函数load(dir,cb){//获取绝对路径consturl=path.resolve(__dirname,dir);常量文件=fs.readdirSync(url);files.forEach(filename=>{filename=filename.replace('.js','');constfile=require(url+'/'+filename);cb(filename,file);})}constloadModel=(config)=>{return(app)=>{mongoose.connect(config.db.url,config.db.options);constconn=mongoose.connection;conn.on('error',()=>{console.error('connectionfailed')})app.$model={}load('../model',(filename,{schema})=>{console.log('loadmodel'+filename,schema)app.$model[filename]=mongoose.model(filename,schema)})}}module.exports={loadModel}以上步骤可以定义数据模型在mongo数据库,接下来就是将数据模型映射到接口5.定义接口名称./framework/router.jsconstrouter=require('koa-router')();const{init,get,create,update,del,}=require('./api');router.get('/api/:listna我',init,get);router.post('/api/:listname',init,create);router.put('/api/:listname/:id',init,update);router.delete('/api/:listname/:id',init,del);module.exports=router.routes();6.接口的具体处理./framework/api.jsmodule.exports={asyncinit(ctx,next){console.log('init',ctx.params);constmodel=ctx.app.$model[ctx.params.listname];如果(模型){ctx.listname=模型;等待下一个();}else{ctx.body='nothismodel'}},asyncget(ctx){ctx.body=awaitctx.listname.find({})},asynccreate(ctx){constreq=awaitctx.listname.create(ctx.request.body)console.log('req',req);console.log('ctx',ctx.listname);ctx.body=req;},异步更新(ctx){constres=awaitctx.listname.updateOne({_id:ctx.params.id},ctx.request.body);ctx.body=res;控制台日志('资源',资源);},asyncdel(ctx){constres=awaitctx.列表名称。deleteOne({_id:ctx.params.id})ctx.身体=资源;},异步页面(ctx){控制台。日志('页面...',ctx.params.page);ctx.body=awaitctx.listname.find({})},}至此使用postman访问接口可以看到对应的效果http://localhost:3000/api/user