简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM