Home > database >  Why spread operator is showing only the last entered data in a for loop?
Why spread operator is showing only the last entered data in a for loop?

Time:06-04

In a GET request I am using a spread operator in a for loop but it is showing only the last entered data only(data about seats) from the database.

The GET request:

router.get("/trip/single", async (req, res) => {
  if (!req.query.from || !req.query.to || !req.query.date) {
    return res.send({
      error: "Please enter the data to get the trip",
    });
  }
  const { from, to, date } = req.query;

  const routes = await Route.find({
    "Location.from": from,
    "Location.to": to,
    date: date.toString(),
  });

  const matchedBus = await routes.filter(() => {
    return Route.busId === routes._id;
  });

  const bookings = await Booking.find({
    routeId: { $in: matchedBus.map((matchedBus) => matchedBus._id) },
  });
  const busIdWithSeatsObj = {};

  for (let i = 0; i < matchedBus.length; i  ) {
    let currentBusSeats = [];
    const busBookings = routes.map((route) => {
      return route.date === date && route.busId === matchedBus[i].busId;
    });
    bookings.forEach((booking) => {
      currentBusSeats = [...booking.seatNumbers];
    });

    busIdWithSeatsObj[matchedBus[i].busId] = currentBusSeats;
  }
  res.status(200).send({ routes, matchedBus, busIdWithSeatsObj });
});

I have two collections into the database:

{"_id":{"$oid":"629a0efd4202a387c33186f9"},
"userId":{"$oid":"629a0e044202a387c33186e7"},
"routeId":{"$oid":"629a0ea54202a387c33186f5"},
"passengers": [{"name": "mitul","gender": "male","age": 25, "_id": {"$oid": "629a0efd4202a387c33186fa"}}],
"phone": 7984154363,
"email":"[email protected]",
"bookingDate":"2022-06-01",
"fare": 2500,
"seatNumbers": [1, 2, 3, 4, 5],
"departureDetails": [{"city": "surat","location": "kapodra","time": "8:00:00", "date": "2022-06-03","_id": {"$oid": "629a0efd4202a387c33186fb"}}],
"arrivalDetails": [{"city":"bhavnagar", "location": "paravadi", "time": "12:00:00", "date": "2022-06-03","_id": {"$oid":"629a0efd4202a387c33186fc"}}],
"createdAt":{"$date":"2022-06-03T13:39:09.223Z"},
"updatedAt":{"$date": "2022-06-03T13:39:09.223Z"},
"__v": 0}


{"_id": {"$oid": "629ac54b13b8d8cd52fc743d"},
"userId":{"$oid":"629a0e044202a387c33186e7"},
"routeId":{"$oid":"629a0ea54202a387c33186f5"},
"passengers":[{"name": "dhaval", "gender": "male", "age": 24, "_id": { "$oid": "629ac54b13b8d8cd52fc743e" }}],
"phone": 7984154363,
"email":"[email protected]",
"bookingDate": "2022-06-04",
"fare": 1000,
"seatNumbers": [14, 15],
"departureDetails":[{"city": "surat", "location": "laskana", "time":"8:00:00", "date": "2022-06-03", "_id": { "$oid": "629ac54b13b8d8cd52fc743f" }}],
"arrivalDetails": [{"city": "bhavnagar", "location": "sukhpar", "time": "12:00:00", "date": "2022-06-03", "_id": { "$oid": "629ac54b13b8d8cd52fc7440" }}],
"createdAt": {"$date": "2022-06-04T02:36:59.215Z"},
"updatedAt": {"$date": "2022-06-04T02:36:59.215Z"},
"__v": 0}

In this collections both have same routeId.

I should get this result with all the seats that are already booked for this particular bus:

{
    "routes": [
        {
            "Location": {
                "from": "629a0e544202a387c33186f2",
                "to": "629a0e294202a387c33186ef"
            },
            "_id": "629a0ea54202a387c33186f5",
            "busId": "629a0e184202a387c33186ec",
            "date": "2022-06-03",
            "departureTime": 8,
            "arrivalTime": 12,
            "createdAt": "2022-06-03T13:37:41.993Z",
            "updatedAt": "2022-06-03T13:37:41.993Z",
            "__v": 0
        }
    ],
    "matchedBus": [
        {
            "Location": {
                "from": "629a0e544202a387c33186f2",
                "to": "629a0e294202a387c33186ef"
            },
            "_id": "629a0ea54202a387c33186f5",
            "busId": "629a0e184202a387c33186ec",
            "date": "2022-06-03",
            "departureTime": 8,
            "arrivalTime": 12,
            "createdAt": "2022-06-03T13:37:41.993Z",
            "updatedAt": "2022-06-03T13:37:41.993Z",
            "__v": 0
        }
    ],
    "busIdWithSeatsObj": {
        "629a0e184202a387c33186ec": [
            1,
            2,
            3,
            4,
            5,
            14,
            15
        ]
    }
}

But instead I am getting this result with last entered data only:

{
    "routes": [
        {
            "Location": {
                "from": "629a0e544202a387c33186f2",
                "to": "629a0e294202a387c33186ef"
            },
            "_id": "629a0ea54202a387c33186f5",
            "busId": "629a0e184202a387c33186ec",
            "date": "2022-06-03",
            "departureTime": 8,
            "arrivalTime": 12,
            "createdAt": "2022-06-03T13:37:41.993Z",
            "updatedAt": "2022-06-03T13:37:41.993Z",
            "__v": 0
        }
    ],
    "matchedBus": [
        {
            "Location": {
                "from": "629a0e544202a387c33186f2",
                "to": "629a0e294202a387c33186ef"
            },
            "_id": "629a0ea54202a387c33186f5",
            "busId": "629a0e184202a387c33186ec",
            "date": "2022-06-03",
            "departureTime": 8,
            "arrivalTime": 12,
            "createdAt": "2022-06-03T13:37:41.993Z",
            "updatedAt": "2022-06-03T13:37:41.993Z",
            "__v": 0
        }
    ],
    "busIdWithSeatsObj": {
        "629a0e184202a387c33186ec": [
            14,
            15
        ]
    }
}

CodePudding user response:

In the for loop you are overwriting the currentBusSeats array with a new array instead of appending to it. You create a new array and overwrite the old currentBusSeats here:

currentBusSeats = [...booking.seatNumbers];

To add to the booking.seatNumbers you can use Array.push:

currentBusSeats.push(...booking.seatNumbers);

Side note: Now you can also declare currentBusSeats as a const instead of a variable with let, which would have helped you debugging by getting an error that you tried to overwrite an array (Assignment to constant variable). I think it is good practice to always declare objects and arrays as constants because you hardly want to overwrite them, only change the values.

  • Related