1

How I can inject new models from boot script?

At the moment I have model-config.json where model are configurated, but is it possible to inject those from boot script?

model-config.json

"MyModel": {
    "dataSource": "db",
    "public": true
}

my-model-bootscript.js

How I can do the same in bootscript?
user257980
  • 1,059
  • 2
  • 15
  • 31
  • 2
    Possible duplicate of [Dynamic Models in Loopback](https://stackoverflow.com/questions/49914970/dynamic-models-in-loopback) – Marvin Irwin Feb 03 '19 at 20:27

1 Answers1

1

Here is a sample code similar to what we use in our project to create models from a boot script:

const modelDefinition = {
    name: "ModelName",
    properties: {
        modelProperty1: {
            type: "string", required: true,
        },
    },
    hidden: ["id"],
    mixins: {
    },
    dataSource: "memory", // or one of your datasources
};

// here we dynamically create create model
loopback.createModel(modelDefinition);
Peter Liapin
  • 1,196
  • 9
  • 20
  • is it possible to load defination from .json? This way I could define models as features. – user257980 Feb 08 '19 at 20:28
  • sure, you can place a json structure into a .json file and then read it into the modelDefinition variable using like: `var fs = require('fs'); var obj = JSON.parse(fs.readFileSync('file', 'utf8'));` You can see more ways [how to read json from file with Node.js here](https://stackoverflow.com/questions/10011011/using-node-js-how-do-i-read-a-json-file-into-server-memory). – Peter Liapin Feb 08 '19 at 21:17