Vijitha
Vijitha

Reputation: 21

Dynamic Models in Loopback

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.

Upvotes: 2

Views: 1069

Answers (1)

The Alpha
The Alpha

Reputation: 146191

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:

enter image description here

Upvotes: 5

Related Questions