Lucid model loop in controller

Hello,

When looping through Lucid models in a controller, how do I access the model itself? So for example I’ve tried:

let lobbies = await Lobby.all();

for(let i in lobbies) {
let lobby = lobbies[i]
console.log(lobby.name) //i want to get the name but doesn’t work
}

I’ve also tried a standard for loop and forEach but can’t get either to work. I’m sure I’m missing something simple.

Thanks in advance!

1 Like

Do you get any error?
Can you post the Lobby model here?

Hi, thanks for the response. I’m not getting any errors, I just can’t seem to figure out how to access attributes of the model such as the name and the id. I don’t have access to the code currently but the Model is just a default one created with an adonis command.

Thanks

for ... in is a wrong statement.

See docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

What you want is a forEach of just use a regular for loop.

Ok, so the problem is you have to iterate over lobbies.rows in order to obtain access to you Lucid model
just make a console.log(lobbies) on your lobbies to see what you have in there

so your code will become something like this:

for(let i in lobbies.rows) {
    const lobby = lobbies.rows[i]
    console.log(lobby.name) // you should be able to have access to name now
}
1 Like

for … in is not the same as foreach or for. The former is for objects, while the latter two options are for arrays.

That works, thanks a lot!

you’re welcome :slight_smile:

this solution it has worked for me, thank you @melokki.

1 Like