Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define embedded properties in Loopback Model definition JSON file

According to Loopback Documentation, we can define embedded document properties programmatically such as:

var UserModel = {
    firstName: String,
    lastName: String,
    address: {
      street: String,
      city: String,
      state: String,
      zipCode: String
    },
    ...
}

or

var AddressModel = {
    street: String,
    city: String,
    state: String,
    zipCode: String
};
var Address = ds.define('Address', AddressModel);
var UserModel = {
    firstName: String,
    lastName: String,
    address: 'Address',
    ...
}
// or address: Address
var User = ds.define('User', UserModel);

My question is whether we can also do it in the Model definition JSON file.

I found that you can create an other JSON file and then reference it directly in the module definition file as type. ex.

{
"name": "Address",
"base": "Model",
"strict": true,
"idInjection": false,
"properties": {
  "id": false,
  "street": {
    "type": "string"
  },
  "city": {
    "type": "string"
  },
  "state": {
    "type": "string"
  },
  "zipCode": {
    "type": "string"
  },
  "country": {
    "type": "string"
  }
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

and then reference it the original JSON definition of User such as

address:{
    type:'Address'
}

But I haven't found how to directly declare it inside one JSON definition without requiring a different file. (Same as programmatically first example)

I have tried

address:{
    street: 'string',
    city: 'string'
    ...
}

but with no result. Data does not get verified and it considers it as an any type property that can save anything

like image 441
mitsos1os Avatar asked Dec 04 '25 07:12

mitsos1os


1 Answers

Actually It seems that you can define sub document properties in Model Definition JSON file the way I mentioned like:

address:{
    street: 'string',
    city: 'string'
    ...
}

The problem is that this anonymous model is defined with no strict option, which defaults it to false, so any other property is also allowed...

I have also created an issue about this being fixed somehow in order to easily create subdocs without creating a separate separate definition JSON file.

Github issue

like image 62
mitsos1os Avatar answered Dec 07 '25 21:12

mitsos1os



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!