Save () does not return the saved id

Hello, what is happening, what happens is that I am using fronted react js, and it is connected to my backend (adonis.js) by means of api, what happens is that when inserting a record, I return that saved record , but it does not return the primary id of that record, try with

 static get visible() {
        return ['id', 'name']
    }

but this is not working, I do not know how to access that registered primary value

Can u share what exactly you trying to do? As your controller.

In Controller call model

await Person.addPerson(info)

In Model

  static addPerson(info) {
        const person = new Person()
        person.name = info.name
        person.save()

        return person
    }

but the model does not debug the id of the record that I’m saving

Thanks.

you need change static async addPerson and await person.save()

1 Like

Curious why you’re not using the existing create() method…

If Person is a proper adonis model, all you ought to be doing here is (in your controller):

const Person = use('App/Models/Person')

async store ({ request }) {
  const person = await Person.create(
    request.only(['name'])
  )

  return response.created(person)
}

Then assuming you’re hitting the route that calls that store method on your controller, it’ll create a new person, with specified name, save it, and return the person object (with id, etc) with a 201 status.

But yeah, as codiplace sort of alluded to, you must use async/await as DB interactions are asynchronous. Which is why you’re not getting the ID in your person object in your response… but, seems you’re also not really using adonis the way it’s meant to be used either :wink:

3 Likes