Search code examples
javascriptnode.jsapiloopbackjs

Change the default order of retrieval in loopback


I have a loopback api that retrieves some objects. These objects has a property createdAt. I want to change the order of the objects that are retrieved by the api based on this property. What is the best way to achieve this??


Solution

  • You can use the order filter in several ways, on your :

    REST API :

    This is for one property and you can choose ASC or DESC :

    filter[order]=createdAt <ASC|DESC>
    

    This is for more than one property :

    filter[order][0]=createdAt <ASC|DESC>&filter[order][1][updatedAt]=<ASC|DESC>...
    

    NODE API

    model.find({
      order: 'createdAt DESC',
    });
    

    HERE the official documentation of the explanation above.

    MODEL DEFINITION JSON

    You can use the scope property in your JSON model file and I recommend it.

    "scope": {
        "order": "createdAt ASC",
        "where": {
          "field": "something" // you can use the where filter also ...
        }
      },
    

    Check this official documentation for more information about SCOPES