乐趣区

关于node.js:mongo定义Schema并灵活创建读取mongo33

1. 配置

conf.js

module.exports = {
    db: {
        url: 'mongodb://127.0.0.1:27017/local',
        options: {useNewUrlParser: true,}
    }
}
2. 入口

index.js

const Koa = require('koa');
const app = new Koa();
const config = require('./conf')
const {loadModel} = require('./framework/loader')

// 加载 model 的配置对应字段
loadModel(config)(app)

// 引入动静配置的 api
const rest = require('./framework/router');
// 主动将传入的 body 字符串转换对象值,cxt.request.body
const bodyParser = require('koa-bodyparser');   

app.use(bodyParser());
app.use(rest);

const port = 3000;
app.listen(port, () => {console.log('link 3000');
})
3. 定义 Schema

./model/user.js

module.exports = {
    schema: {
        mobile: {
            type: String,
            required: true,
        },
        realName: {
            type: String,
            required: true,
        },
    }
}
4. 加载定义的 Schema 文件,并读取配置到 mongo

./framework/loader.js

const fs = require('fs');
const path = require('path');
const mongoose = require('mongoose');

function load (dir, cb) {
    // 获取绝对路径
    const url = path.resolve(__dirname, dir);
    const files = fs.readdirSync(url);
    files.forEach(filename => {filename = filename.replace('.js', '');
        const file = require(url + '/' + filename);
        cb(filename, file);
    })
}

const loadModel = (config) => {return (app) => {mongoose.connect(config.db.url, config.db.options);
        const conn = mongoose.connection;
        conn.on('error', () => {console.error('连贯失败')
        })
        app.$model = { }
        load('../model', (filename, {schema}) => {console.log('load model'+ filename, schema)
            app.$model[filename] = mongoose.model(filename, schema)
        })
    }
}
module.exports = {loadModel}

以上步骤,即可定义在 mongo 数据库中的数据模型,接下来是将数据模型和接口对应

5. 定义接口名称

./framework/router.js

const router = require('koa-router')();
const {init, get, create, update, del,} = require('./api');

router.get('/api/:listname', 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.js

module.exports = {async init (ctx, next) {console.log('init', ctx.params);
        
        const model = ctx.app.$model[ctx.params.listname];
        if (model) {
            ctx.listname = model;
            await next();} else {ctx.body = 'no this model'}
    },
    async get (ctx) {ctx.body = await ctx.listname.find({})
    },
    async create (ctx) {const req = await ctx.listname.create(ctx.request.body)
        console.log('req', req);
        console.log('ctx', ctx.listname);
        
        ctx.body = req;
    },
    async update (ctx) {
        const res = await ctx.listname.updateOne({_id: ctx.params.id}, ctx.request.body);
        ctx.body = res;
        console.log('res', res);
    },
    async del (ctx) {
        const res = await ctx.listname.deleteOne({_id: ctx.params.id})
        ctx.body = res;
    },
    async page (ctx) {console.log('page...', ctx.params.page);
        
        ctx.body = await ctx.listname.find({})
    },
}

至此,用 postman 去拜访接口即可看到对应成果
http://localhost:3000/api/user

退出移动版