Dynamic Models in Loopback

拈花ヽ惹草 提交于 2019-12-11 00:56:08

问题


How to create a dynamic models in loopback, instead of using the command "lb model" for all models.

For ex: If I want to create 30 models with almost same properties, will be in trouble of creating all the 30 models and those corresponding properties again and again.

Is it possible to create the model and iterate it to another model using loopback. Kindly share your answers.


回答1:


Well, I'm still new to this but I think, you can easily create any number of dynamic models programmatically. For example, at first, create a boot script inside your boot directory, ex: server\boot\dynamic-models.js and then create a dynamic model using the following code:

const app = require('../server');
const dbDataSource = app.datasources.db;
const schema = {
    "name": {
      "type": "string",
      "required": true
    },
    "email": {
      "type": "string",
      "required": true
    }
};

const MyDynamicModel = dbDataSource.createModel('MyDynamicModel', schema);

app.model(MyDynamicModel);

The app is exported from projectroot/server/server.js, so you can require it in your script.

Also, the schema is optional (in case of noSql/mongo). Once you create the dynamic models then you can visit your api explorer and can see the dynamically created models/endpoint.

If you've more models to create then all you need to do a loop and create the models, for example:

const models = ['ModelOne', 'ModelTwo'];
// or export from other files and import those here, i.e:
// const schema = require('exported-from-another-file');
// const models = require('exported-from-another-file');
models.forEach(model => {
    app.model(dbDataSource.createModel(model, schema));
});

Update: Another working example for multiple models to register dynamically:

// project-root/common/dynamic/index.js
module.exports.schema = {
    "name": {
        "type": "string",
        "required": true
    },
    "email": {
        "type": "string",
        "required": true
    }
};

module.exports.models = [
    'ModelOne',
    'ModelTwo'
];
// project-root/server/boot/dynamic-models.js
const app = require('../server');
const dbDataSource = app.datasources.db;
const {schema, models} = require('../../common/dynamic');
models.forEach(
    model => app.model(dbDataSource.createModel(model, schema))
);

Now on, to add any dynamic model using the same schema, all you need to add a model name in the models array. This is tested and works fine:



来源:https://stackoverflow.com/questions/49914970/dynamic-models-in-loopback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!