diff --git a/README.md b/README.md index de8e77f..2fddc90 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,8 @@ exports.mongoose = { }; // recommended exports.mongoose = { + //baseDir:'model', //models in `app/${model}` + //delegate:'model' //lood to `app[delegate]` client: { url: 'mongodb://127.0.0.1/example', options: {}, diff --git a/app/extend/context.js b/app/extend/context.js deleted file mode 100644 index 0bf2077..0000000 --- a/app/extend/context.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -module.exports = { - get model() { - return this.app.model; - }, -}; diff --git a/config/config.default.js b/config/config.default.js index 26ea6e2..a3b1ad3 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -14,4 +14,6 @@ exports.mongoose = { loadModel: true, app: true, agent: false, + baseDir: 'model', // models in `app/${model}`,the deafault is `app/model` + delegate: 'model', // lood to `app[delegate]`,the deafault is app.model }; diff --git a/lib/mongoose.js b/lib/mongoose.js index 8414740..71c0782 100644 --- a/lib/mongoose.js +++ b/lib/mongoose.js @@ -11,7 +11,7 @@ let count = 0; const globalPlugins = []; module.exports = app => { - const { client, clients, url, options, defaultDB, customPromise, loadModel, plugins } = app.config.mongoose; + const { client, clients, url, options, defaultDB, customPromise, loadModel, plugins, delegate } = app.config.mongoose; // compatibility if (!client && !clients && url) { @@ -48,6 +48,21 @@ module.exports = app => { app.mongoose.loadModel = () => loadModelToApp(app); + const ctx = app.context; + const DELEGATE = Symbol(`context#mongoose_${delegate}`); + Object.defineProperty(ctx, delegate, + { + get() { + // context.model is different with app.model + // so we can change the properties of ctx.model.xxx + if (!this[DELEGATE]) { + this[DELEGATE] = Object.create(app[delegate]); + this[DELEGATE].ctx = this; + } + return this[DELEGATE]; + }, + configurable: true, + }); if (loadModel) { app.beforeStart(() => { loadModelToApp(app); @@ -114,8 +129,9 @@ function createOneClient(config, app) { } function loadModelToApp(app) { - const dir = path.join(app.config.baseDir, 'app/model'); - app.loader.loadToApp(dir, 'model', { + const config = app.config.mongoose; + const dir = path.join(app.config.baseDir, 'app', config.baseDir); + app.loader.loadToApp(dir, config.delegate, { inject: app, caseStyle: 'upper', filter(model) {