add missing fields to model

This commit is contained in:
Thomas Ruoff
2020-08-01 14:30:49 +02:00
parent 7cac6055ce
commit 4089fcc944
2 changed files with 40 additions and 9 deletions

View File

@@ -17,23 +17,47 @@ export const Booker = mongoose.model('Booker', BookerSchema)
export const Booking = mongoose.model('Booking', BookingSchema)
export async function getBookedDays() {
const bookings = await Booking.find({
status: { $ne: 'rejected' },
$or: [{ endDate: { $gt: new Date() } }, { startDate: { $gt: new Date() } }],
}).exec()
const bookings = await Booking.find(
{
status: { $ne: 'rejected' },
$or: [
{ endDate: { $gt: new Date() } },
{ startDate: { $gt: new Date() } },
],
},
'startDate endDate'
).exec()
return bookings.map((booking) => booking.days).flat()
}
export async function createBooking({ name, email, startDate, endDate }) {
export async function createBooking({
startDate,
endDate,
purpose,
org,
destination,
name,
email,
street,
zip,
city,
}) {
const booking = new Booking({ startDate, endDate, purpose, org, destination })
const bookedDays = await getBookedDays()
if (booking.days.some((day) => bookedDays.includes(day))) {
throw new mongoose.Error.ValidationError(booking)
}
const ignoreCaseEmailMatcher = new RegExp(email, 'i')
let booker = await Booker.findOne({ email: ignoreCaseEmailMatcher }).exec()
if (!booker) {
booker = new Booker({ name, email })
booker = new Booker({ name, email, street, zip, city })
await booker.save()
}
const booking = new Booking({ startDate, endDate, booker: booker._id })
booking.booker = booker._id
await booking.save()
await booking.populate('booker').execPopulate()
return booking.toJSON()