jpoveda
jpoveda

Reputation: 2177

Loopback and MongoDB Embedded Documents Defining JSON Model

Can / how do you define an embedded document in a model's json definition with LoopbackJS without creating a model to represent the sub-document?

For example, consider this following MongoDB document:

 {
      _id: ObjectId("some_mongodb_id"),
      subDocs: [
           {
                "propertyA": "a1",
                "propertyB": "b1"
           },
           {
                "propertyA": "a2",
                "propertyB": "b2"
           }
      ]
 }

I could create two models in loopback:

 some-model.json:
      ...
      "properties": {
           "subDocs": [
                "SubDocsModel"
           ]
      }

 sub-docs-model.json:
      ...
      "properties": {
           "propertyA": "string",
           "propertyB": "string"
      }

Rather than doing that, however, I'd like to just declare the sub-doc model inline in the some-model.json since it's just there to document the shape of some-model's document.

Is that possible? Something like:

 some-model.json:
 ...
 "properties":{
      "subDocs": [
           {
                "propertyA": {
                     "type": "string"
                },
                "propertyB": {
                     "type": "string"
                }
           }
      ]
 }

I tried the above, but what I end up with is a field in my mongodb document that's of type string with the value [object Object]...

The purpose would be (1) to document the shape of the sub-document, and (2) to allow for validation by loopback without adding custom logic.

Upvotes: 1

Views: 652

Answers (1)

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

You can define it as an object

some-model.json:

"properties": {
       "subDocs": ["object"]
  }

But if you want validation or have a structure for sub-docs, you need to create a loopback model for that.

Loopback does not do any validation, ... for properties with type object.

Upvotes: 1

Related Questions