how to parse the result of a query in a loopback model

20 views
Skip to first unread message

Irnel Victoria

unread,
Apr 16, 2018, 10:08:40 AM4/16/18
to loopb...@googlegroups.com

Hi everyone

I have this problem, I want to use a database connector, because I have to perform a complex query, and I want to parse or convert the result into a loopback model (persistent model).


For example, suppose that the query returns this: cityname, citystate,
codestate, postalcode etc

and on the other hand we have a loopback model with these properties:

{
  "name": "cities",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "cityName": {
      "type": "string",
      "required": true
    },
    "cityState": {
      "type": "string",
      "required": true
    },
    "codeState": {
      "type": "string",
      "required": true
    },
    "postalCode": {
      "type": "string",
      "required": false
    }
    ....
}

I would like to parse the result of the query in a persistent model.

the loopback framework does it, because the methods findByID, find,
findOne etc, do it. I use a datasource with the postgres connector,
try to see how they do it in the loopback core but I could not
understand much.


Areas.getAreaByCityId = (cityId, cb) => {
     postgreDS.connector.execute (SqlStatement.getAreaByCityId (), [cityId], (err, queryResult) => {
       if (err)
         return cb (err);
       else if (queryResult.length <1) // empty query (0 records)
         return cb (ErrorMessage.getErrorMessage (
           "No area was found with id" + cityId, TypeError.ModelNotFound));
       else
         return cb (null, queryResult [0]);
     });
   };

I want to parse the result of the query (queryResult) in a loopback model.
How I do this.


mbaj...@gmail.com

unread,
Apr 23, 2018, 9:24:18 AM4/23/18
to LoopbackJS
Hi Irnel,

You can simply pass model data to a model constructor in order to create a new instance.

Assuming your method is returning data for your "cities" model as described earlier:

Areas.getAreaByCityId = (cityId, cb) => {
     const Cities = Areas.app.models.Cities;

     postgreDS.connector.execute (SqlStatement.getAreaByCityId (), [cityId], (err, queryResult) => {
       if (err)
         return cb (err);
       else if (queryResult.length <1) // empty query (0 records)
         return cb (ErrorMessage.getErrorMessage (
           "No area was found with id" + cityId, TypeError.ModelNotFound));
       else
         return cb (null, new Cities(queryResult [0]));
     });
   };

Miroslav
Reply all
Reply to author
Forward
0 new messages