Hkm Sadek
Hkm Sadek

Reputation: 3209

Array length undefined in nodejs application

I have been trying to understand whats wrong in my code. Please have a look, may be I am missing something.

    const images = await Image.query().where('product_id', product.id).fetch()
    for(let i=0; i< images.length; i++){
        console.log(images[i]) // never comes in.... 
        console.log('Inside in')
    }
    console.log(images.length) // it shows undefined...
    console.log(images)
    return images

But I can see my data in browser like this

(2) [{…}, {…}]

If I console.log(images) I see in my terminal something like this

   VanillaSerializer {
   rows: 
   [ Image {
   __setters__: [Array],
   '$attributes': [Object],
   '$persisted': true,
   '$originalAttributes': [Object],
   '$relations': {},
   '$sideLoaded': {},
   '$parent': null,
   '$frozen': false,
   '$visible': undefined,
   '$hidden': undefined },
 Image {
   __setters__: [Array],
   '$attributes': [Object],
   '$persisted': true,
   '$originalAttributes': [Object],
   '$relations': {},
   '$sideLoaded': {},
   '$parent': null,
   '$frozen': false,
   '$visible': undefined,
   '$hidden': undefined } ],
  pages: null,
  isOne: false }

I am running nodejs with adonis js framework.

Thank you

Upvotes: 0

Views: 409

Answers (1)

Inus Saha
Inus Saha

Reputation: 1918

you should use the toJSON() function of VanillaSerializer to return the data as json, like the following.

 const imageData = await Image.query().where('product_id', product.id).fetch();
 const images = imageData.toJSON();

then you can loop through the images like you did.

Upvotes: 1

Related Questions