I have a problem with creating array of objects in a while loop. I create an object newDay
with date starting from today and slotsId
object, which is a mongo Id object. I am trying to create array of custom Day objects using while loop. In each itaration I'm creating newDay
and then I push it into daysArray
and then increase . When I log each day before performing push, it logs as intended - each day has unique date. But after finishing the loop, all days in array have the same date - date of last pushed day. I really have no clue what is going on. What am I missing?
Day object:
class Day implements ISingleDay {
date: Date;
workday: boolean;
slots: mongoose.Types.ObjectId | null;
_id: mongoose.Types.ObjectId
validateHoliday() {
const dateDay = String(this.date.getDate()).padStart(2, '0');
const dateMonth = String(this.date.getMonth() + 1).padStart(2, '0');
const dateYear = String(this.date.getFullYear());
const monthAndDay = dateMonth + '-' + dateDay;
const currentDate = new Date(dateYear + '-' + monthAndDay);
if (currentDate.getDay() === 0 || currentDate.getDay() === 6 || holidays.includes(monthAndDay)) {
return false;
} else {
return true;
}
}
constructor(date: Date, slots: mongoose.Types.ObjectId) {
this.date = date;
this.workday = this.validateHoliday();
this._id = new mongoose.Types.ObjectId()
if (this.validateHoliday()) {
this.slots = slots;
} else {
this.slots = null;
}
console.log(this.date)
}
}
Note: method validateHoliday() in this form is temporary.
Function I'm talking about:
export function createDayArray(doctorId: mongoose.Types.ObjectId, daysId: mongoose.Types.ObjectId, firstname: string, lastname: string) {
const slotsArray = createSlotArray();
const dayCount = workdaySettings.days.dayCount || 30;
const daysArray: Day[] = [];
const todayNonUTC = new Date();
const date = new Date(Date.UTC(todayNonUTC.getUTCFullYear(), todayNonUTC.getUTCMonth(), todayNonUTC.getUTCDate(), 0, 0, 0, 0));
while (daysArray.length <= dayCount) {
const dayId = new mongoose.Types.ObjectId();
const slotsId = new mongoose.Types.ObjectId();
const newDay = new Day(date, slotsId);
daysArray.push(newDay);
date.setDate(date.getDate() + 1);
new Slots({
_id: slotsId,
doctorId: doctorId,
dayId: dayId,
slots: slotsArray
}).save()
}
new Days({
_id: daysId,
doctorId: doctorId,
doctorName: `${firstname} ${lastname}`,
days: daysArray
}).save()
}