Home > Blockchain >  Problem: TypeError: Cannot read properties of undefined (reading 'id')
Problem: TypeError: Cannot read properties of undefined (reading 'id')

Time:12-06

Hope you all are doing well.

I have this error in my terminal:

    console.log(data[x].id, "|||", data[x].name, "|||", data[x].photo, "|||", data[x].short_effect);
                        ^
    TypeError: Cannot read properties of undefined (reading 'id')

My function:

import {MongoClient} from "mongodb";

const urlMongoDb = "myUrl"

async function getAllData() {

    const client = new MongoClient(urlMongoDb,{ useNewUrlParser: true, useUnifiedTopology: true });

    try {
      const database = client.db("dbName");
      const itemsDb = database.collection("test");

      const data = await itemsDb.find({}).toArray();

      for (var x = 0; x <= data.length; x  ) {
        
        console.log(data[x].id, "|||", data[x].name, "|||", data[x].photo, "|||", data[x].short_effect);

      }

    } finally {
      await client.close();
    }
}

getAllData();

Can you please help me to resolve it. Thanks <3

CodePudding user response:

The error you are seeing is because you are trying to access properties of undefined in your for loop. This is happening because you are using the <= operator in your loop condition, which will cause the loop to run one extra time after it has reached the end of the data array.

To fix this, you should change the <= operator to the < operator in your for loop. This will prevent the loop from running one extra time after it has reached the end of the data array, and it will prevent you from trying to access properties of undefined in the loop.

Here is the updated code:

Copy code

import {MongoClient} from "mongodb";

const urlMongoDb = "myUrl"

async function getAllData() {

    const client = new MongoClient(urlMongoDb,{ useNewUrlParser: true, useUnifiedTopology: true });

    try {
      const database = client.db("dbName");
      const itemsDb = database.collection("test");

      const data = await itemsDb.find({}).toArray();

      for (var x = 0; x < data.length; x  ) { // change <= to <
        
        console.log(data[x].id, "|||", data[x].name, "|||", data[x].photo, "|||", data[x].short_effect);

      }

    } finally {
      await client.close();
    }
}

getAllData();`

This should fix the error and allow your code to run as expected.

  • Related