Search code examples
javascriptpostgresqlloopback

Populating Loopback models with existing data


I've got an array of model data in JSON from a Postgres SQL query in Loopback.

I want to be able to populate loopback models with this data directly - which presumably the loopback-datasource-juggler already does in the dao.js component.

Unfortunately, I've not been able to make this work. Here's what I've got so far:

app.dataSources.Db.connector.execute(sql, null, (err, modelsRaw) => {
   // Fetch the data in the right casing for the model
   const preparedModels = modelsRaw.map(modelRaw => app.dataSources.Db.connector.fromRow('myModel', modelRaw))
   // Now I'm lost...
   const model = app.dataSources.Db.connector.getDataAccessObject()  // returns null
   app.dataSources.Db.connector.getDataAccessObject(preparedModels[0]) //returns {}
})

Does anyone know how to return Loopback models from here?


Solution

  • Turns out the answer was fairly easy

    app.dataSources.Db.connector.execute(sql, null, (err, modelsRaw) => {
    const models = modelsRaw.map(modelRaw => {
      const preparedModel = app.dataSources.Db.connector.fromRow('myModel', modelRaw)
      return new app.models.myModel(preparedModel)
    })
    

    Hope that helps someone