Reputation: 1
I am trying to model the following using embedsOne relation:
var modelName = 'Customer';
var results = {};
results[modelName] = {
"name": modelName,
options: {
idInjection: false
},
properties: {
"custid": {
"required": true,
"type": "string",
"id":1,
"length": 30
},
"name": {
"required": true,
"type": "number",
"id":1,
"length": 30
},
"address":{
"required": true,
"type": "object",
"properties": {
"city": {
"required": true,
"type": "string",
"length": 30
}
}
}
}
};
I used the following code to create the embedsOne relations between Customer (Parent model) and the Address (being child model)
modelProps = results[modelName].properties;
Object.keys(modelProps).forEach(function (field) {
if(modelProps[field].type === "object") {
childProps = modelProps[field];
childProps.name = field;
delete modelProps[field];
}});
console.log("modeproper: ",modelProps);
console.log(childProps);
var model1 = {
"name": "Customer",
"plural": childProps.name,
"base": "PersistedModel",
"idInjection": false,
"properties": childProps.properties,
"public": false
};
var childModel = loopback.createModel(model1);
childModel.public = false;
var config = {
dataSource: 'dssodayana',
"public": false
};
app.model(childModel, config);
var model = {
"name": "Customer",
"plural": "Customer",
"base": "PersistedModel",
"idInjection": false,
"properties": modelProps
};
var parentModel = loopback.createModel(model);
app.model(parentModel, config);
console.log();
**parentModel.embedsOne(childModel, {
as: "test", // default to the relation name - address
property: "address" // default to addressItem
});**
app.model(parentModel);
Now, I want to view the parentModel. Is it possible to write this Model to a disk file or convert it to a json?
Upvotes: 0
Views: 888
Reputation: 1607
If you want to create models dynamically based on your database schema you can use this method inside your app start:
ds.discoverModelDefinitions(modelDefinitionsConf, function(err, data){
for (var el in data) {
(function(modelName){
if (acceptedTables.indexOf(modelName) >= 0) {
ds.discoverSchema(modelName, function (err, schema) {
var test = ds.createModel(schema.name, schema.properties, schema.options);
app.model(test, {public : true, dataSource: ds });
});
}
})(data[el].name)
}
});
This will iterate over your tables in provided database source and dynamically create models and expose them in the api.
Upvotes: 1
Reputation: 781
You can use the parentModel.definition.toJSON()
function to print the definition.
Upvotes: 0