TheWebs
TheWebs

Reputation: 12933

loopback 2 - defining an array of objects on a model

if I have a usermodel and I define:

"events": {
  "type": [
    "Object"
  ]
},

Do I need to define anything else in the usermodel.js to be able to post things like: [{name: 'sample', ...}, ...] to the user table's events column?

I ask because if I remove this particular definition from the .json the app compiles and the database migrates, but with it in, the app compiles but the database states there was an issue with the users findByid. My debugging has narrowed it down to this particular set of code.

Upvotes: 3

Views: 2800

Answers (2)

YeeHaw1234
YeeHaw1234

Reputation: 2495

Another way would be to define the object you want in the array as a model, then use that model as your type:

Model: Class

{
    "name": "Class",
    "base": "Model",
    "strict": true,
    "idInjection": false,
    "properties": {
        "label": {
            "type": "string",
            "required": true
        }
    }
}

Model: Student

{
    "name": "Student",
    "base": "PersistedModel",
    "strict": true,
    "idInjection": true,
    "properties": {
        "classes": {
            "type": ["Class"],
            "required": false
        },
    }
}

Upvotes: 3

Rohit Hazra
Rohit Hazra

Reputation: 667

I think you can simply use this structure

{
 "events":{
    "type": [
       {
          "key": "type",
          "key2": "type"
       }
    ]
 }
}

You can see a .js example here and .json example here. but I can also see an issue with the implementation here that says

this model has problem. When we fetch the data with any get call, it renders this particular field as ["Object Object"] even though the data is properly saved in the database.

which I would recommend you to try on your own as it will depend a lot on versions and drivers.

Though I would like to ask that what kind of database are you using?

Upvotes: 7

Related Questions