Jhon Caylog
Jhon Caylog

Reputation: 503

NodeJS item was not added on the index of the object?

Now I have a code below which first query the result from vehicle model and then use the results to query for files and collections and at the end of the line in

if (finalFile) {
    var item = "testdatass"
    veh.data[i].FileData = item
    //item was added here when i try to console log
    console.log("veh.data[i].FileData", veh.data[i])
}

On the line above I tried to assign

veh.data[i].FileData = item

But when I check the data which is the veh.data on the final response, the item was not added.

return res.status(200).send({
    message: "success",
    pageNo: pageNo,
    totalRecords: veh.data.length,
    data: veh.data,
    totalPages: totalPages

})

Full Code

let veh = {
  data: []
}


Vehicle.model.count({}, function(err, totalCount) {
  if (err) {
    response = {
      "error": true,
      "message": "Error fetching data"
    }
  }

  Vehicle.model.find(query, {}, pagination).sort(sortOrd + sortType).exec(function(err, vehicle) {

    if (err || !vehicle) {
      res.json({
        message: err
      })
    }

    var totalPages = Math.ceil(totalCount / size)

    veh.data = vehicle

    MongoClient.connect(url, function(err, client) {

      if (err) {
        return res.render('index', {
          title: 'Uploaded Error',
          message: 'MongoClient Connection error',
          error: err.errMsg
        });
      }

      const db = client.db(dbName);
      const collection = db.collection('fs.files');
      const collectionChunks = db.collection('fs.chunks');

      for (let i = 0; i < veh.data.length; i++) {

        let ImageList = veh.data[i].ImageList.split(',')
        let profile_name = ImageList[0].split('/').pop();

        collection.find({
          $and: [{
              $or: [{
                metadata: veh.data[i].VIN
              }]
            },
            {
              $or: [{
                filename: profile_name
              }]
            }
          ]
        }).toArray(function(err, docs) {
          if (err) {
            return res.render('index', {
              title: 'File error',
              message: 'Error finding file',
              error: err.errMsg
            });
          }
          if (!docs || docs.length === 0) {
            return res.render('index', {
              title: 'Download Error',
              message: 'No file found'
            });
          } else {

            for (let i = 0; i < docs.length; i++) {

              collectionChunks.find({
                  files_id: docs[i]._id
                })
                .toArray(function(err, chunks) {
                  if (err) {
                    return res.render('index', {
                      title: 'Download Error',
                      message: 'Error retrieving chunks',
                      error: err.errmsg
                    });
                  }
                  if (!chunks || chunks.length === 0) {
                    return res.render('index', {
                      title: 'Download Error',
                      message: 'No data found'
                    });
                  }

                  let fileData = []

                  for (let i = 0; i < chunks.length; i++) {
                    fileData.push(chunks[i].data.toString('base64'));
                  }

                  let finalFile = 'data:' + docs[0].contentType + ';base64,' +
                    fileData.join('');

                  if (finalFile) {
                    var item = "testdatass"
                    veh.data[i].FileData = item
                  }


                });
            }
          }
        })
      }
    })

//now on the final data the when i check and logged it the item was not added
console.log("Total Vehicle", vehicle.length)

return res.status(200).send({
  message: "success",
  pageNo: pageNo,
  totalRecords: veh.data.length,
  data: veh.data,
  totalPages: totalPages

})

}) })

Result

    vehicle data [ { _id: 5dba69401fe3d41714eafb62,
        DriveType: 'FWD',
        FuelType: 'Gasoline Fuel',
        ImageList:'',
        Options:
         'Traction Control,Stability Control,Front Wheel Drive,Tires - Front All-Season,Tires - Rear All-Season,Aluminum Wheels,Power Steering,4-Wheel Disc Brakes,ABS,Brake Assist,Sun/Moonroof,Generic Sun/Moonroof,Rear Spoiler,Automatic Headlights,Fog Lamps,Heated Mirrors,Power Mirror(s),Privacy Glass,Intermittent Wipers,Variable Speed Intermittent Wipers,Leather Seats,Power Driver Seat,Bucket Seats,Heated Front Seat(s),Driver Adjustable 
    Lumbar,Passenger Adjustable Lumbar,3rd Row Seat,Pass-Through Rear Seat,Floor Mats,Steering Wheel Audio Controls,Adjustable Steering Wheel,Engine Immobilizer,Tire Pressure Monitor,Power Windows,Power Door Locks,Universal Garage Door Opener,Keyless Entry,Cruise Control,Security System,Climate Control,A/C,Rear A/C,Rear Defrost,AM/FM Stereo,CD Changer,CD Player,Satellite Radio,Entertainment System,Power Outlet,Driver Vanity Mirror,Passenger Vanity Mirror,Driver Illuminated Vanity Mirror,Passenger Illuminated Visor Mirror,Rear Reading Lamps,Driver Air Bag,Passenger Air Bag,Front Side Air Bag,Passenger Air Bag Sensor,Front Head Air Bag,Rear Head Air Bag,Child Safety Locks',
        Description: '',
        DateInStock: '7/15/2019',
        Invoice: 3000,
        BookValue: '3686',
        MSRP: 0,
        SellingPrice: 5592,
        Miles: 162111,
        Transmission: 'Automatic',
        EngineDisplacement: '3.5L',
        EngineCylinders: '6',
        InteriorColor: '',
        ExteriorColor: 'Gray',
        Doors: 4,
        ModelNumber: 'YF2867JNW',
        Trim: 'Ex-L',
        Body: 'Sport Utility',
        Model: 'Piloto',
        Make: 'Honda',
        Year: 2007,
        VIN: '5FNYF28677B037628',
        Stock: 'K2501A',
        Type: 'Used',
        __v: 0,
        state: 'published',
        Certified: true } ]

Upvotes: 2

Views: 119

Answers (2)

Ankur Patel
Ankur Patel

Reputation: 488

You can not call mongodb query inside for loop because loop working sync and mongo query run as async so you can not get your desire output.

Here is your full code with solutions

let veh = {
    data: []
}

Vehicle.model.count({}, function (err, totalCount) {
    if (err) {
        response = {
            "error": true,
            "message": "Error fetching data"
        }
    }

    Vehicle.model.find(query, {}, pagination).sort(sortOrd + sortType).exec(function (err, vehicle) {
        if (err || !vehicle) {
            res.json({
                message: err
            })
        }

        var totalPages = Math.ceil(totalCount / size)

        veh.data = vehicle;

        MongoClient.connect(url, function (err, client) {
            if (err) {
                return res.render('index', {
                    title: 'Uploaded Error',
                    message: 'MongoClient Connection error',
                    error: err.errMsg
                });
            }

            const db = client.db(dbName);
            const collection = db.collection('fs.files');
            const collectionChunks = db.collection('fs.chunks');
            const promise = [];
            let ImageList = veh.data[i].ImageList.split(',')
            let profile_name = ImageList[0].split('/').pop();
            for (let i = 0; i < veh.data.length; i++) {
                promise.push(collection.find({
                    $and: [{
                        $or: [{
                            metadata: veh.data[i].VIN
                        }]
                    },
                    {
                        $or: [{
                            filename: profile_name
                        }]
                    }
                    ]
                }))
            }

            Promise.all(promise)
                .then(docs => {
                    if (!docs || docs.length === 0) {
                        return res.render('index', {
                            title: 'Download Error',
                            message: 'No file found'
                        });
                    } else {
                        const promise = [];
                        for (let i = 0; i < docs.length; i++) {
                            promise.push(collectionChunks.find({
                                files_id: docs[i]._id
                            }))
                        }
                        Promise.all(promise)
                            .then(chunks => {
                                if (!chunks || chunks.length === 0) {
                                    return res.render('index', {
                                        title: 'Download Error',
                                        message: 'No data found'
                                    });
                                }

                                let fileData = []

                                for (let i = 0; i < chunks.length; i++) {
                                    fileData.push(chunks[i].data.toString('base64'));
                                }

                                let finalFile = 'data:' + docs[0].contentType + ';base64,' +
                                    fileData.join('');

                                if (finalFile) {
                                    var item = "testdatass"
                                    veh.data[i].FileData = item
                                }
                                console.log("Total Vehicle", vehicle.length)

                                return res.status(200).send({
                                    message: "success",
                                    pageNo: pageNo,
                                    totalRecords: veh.data.length,
                                    data: veh.data,
                                    totalPages: totalPages

                                })
                            })
                            .catch(error => {
                                return res.render('index', {
                                    title: 'Download Error',
                                    message: 'Error retrieving chunks',
                                    error: err.errmsg
                                });
                            })
                    }
                })
                .catch(error => {
                    return res.render('index', {
                        title: 'File error',
                        message: 'Error finding file',
                        error: error
                    });
                })
        })
    })
})

Upvotes: 1

Jayakumar Thangavel
Jayakumar Thangavel

Reputation: 2005

I suspect issue because of below

 for (let i = 0; i < docs.length; i++) {

inside also for loop variable names are same.

for (let i = 0; i < chunks.length; i++) {

enter image description here

Upvotes: 0

Related Questions