Search code examples
javascriptnode.jsloopbackjsstrongloop

Strongloop API query by base model


We have multiple models with a common base model. E.g. creature as a base, and animal and human as sub models, inheriting from creature.

Is there a ready-to-use method to query for all creatures (be it human or animal) with one API call?


Solution

  • No, not with the built-in methods.

    Models in loopback you should not be viewed as object, they are not made for OOP.

    They do define basic behavior which you can extend later on using custom config & code, but that's it, there is no way to query the parent model. The base model is merely a template for the extending model.

    Instead, use the relation system to define relationship between models. But in your case, you want a ready-to-go method with a single API call, so that means you will need a single Model to host all instances to be queried.

    I would do the following:

    • Creature extends PersistedModel

    And add a property type of type string. Give it human for humans, animal for animals, etc.

    Then, you can get all instances[ with a GET request

    GET /creatures?filter[where][and][0][type]=human&filter[where][and][1][type]=animal
    

    Also see where filter