Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30430

How to cast property in nested objects to ObjectId with loopback and mongodb?

Let's say I have the following model definition:

{
  "name": "Report",
  "idInjection": true,
  "trackChanges": true,
  "mongodb": {
    "collection": "report"
  },
  "properties": {
    "resource" : {"type": "String"},
    "date" : {"type": "Date"},
    "people" : [ {
        // Here's where I like to have an id property.
        "role" : {"type": "String"},
        "hours" : {"type": "Number"}
    } ],
    "name" : {"type": "String"}
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": []
}

Now I want to have id property in each object in people array(to be accessed with like report.people[0].id) and it should be casted to ObjectId on inserts and updates. But well, loopback doesn't have an ObjectId type and the only way seems to be using relations but then how should the foreign key be?

Is there any way to have the id property casted to ObjectId on inserts and updates?

Update:

I tried using embedsMany, but the id wasn't converted:

Here's my report.json:

{
  "name": "Report",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "people" : {
      "type": "embedsMany",
      "model": "ReportPerson",
      "options": {
        "validate": true,
        "autoId": false
      }
    }
  },
  "acls": [],
  "methods": []
}

and here's my report-person.json:

{
  "name": "ReportPerson",
  "base": "Model",
  "idInjection": true,
  "properties": {
    "hours": {"type" : "number"}
  },
  "validations": [{
      "person" : {
          "model": "Person",
          "type": "belongsTo",
          "foreignKey": "id"
      }
  }],
  "relations": {},
  "acls": [],
  "methods": []
}

When I try to insert this Report using the http API:

{
    "name" : "report",
    "people" : [
        {
            "id" : "54c7926e1d621dc65495f069",
            "hours" : 2
        }
    ]
}

The id wouldn't be casted to ObjectId and stays as string on the database.

Upvotes: 2

Views: 3632

Answers (1)

ebarault
ebarault

Reputation: 126

Anyone playing with loopback and mongodb hits this one once in a while. To get around the lack of ObjectId type in loopback: -one way is to indeed describe a relation using the property as a foreign key, as discussed in this post -the other way, much cleaner imo is to define the property as an id in the JSON file

see model definition documentation

for example: { "myId": { "type": "string", "id": true, "generated": true } }

now a request on this property will work either with pass the actuel objectId or its string representation

Upvotes: 1

Related Questions