'How to know if the time of Start and End entered is already between another time of start and end in the database using node js
The idea is that if a user wants to make a reservation, the time of start and end will not be accepted if it's already in the interval of another reservation.
The model:
import mongoose from 'mongoose'
const placeReservationSchema = mongoose.Schema({
username: String,
beginReservation: String,
endReservation: String,
namePlace: String
})
export default mongoose.model('placeReservation', placeReservationSchema)
The code :
function timeToNumber(timeString) {
var hm = timeString.split(":");
var hours = Number(hm[0]);
hours = hours * 60 + Number(hm[1]);
return hours;
}
function timeCompare(min, max, ref) {
return (timeToNumber(min) <= timeToNumber(ref)) && (timeToNumber(ref) <= timeToNumber(max));
}
app.post('/users/reservationn',(req, res) => {
let message = {}
PlaceReservation.find({{ namePlace: req.body.namePlace}},(err, reservation)=>{
if(err){
res.status(500).json({success: false, message: err})
}else{
if(reservation){
if(timeCompare(reservation.beginReservation, reservation.endReservation,req.body.beginReservation) === true){
message.beginReservationM = 'BR_TAKEN'
}
if(timeCompare(reservation.beginReservation, reservation.endReservation,req.body.endReservation) === true){
message.endReservationM = 'ER_TAKEN'
}
res.status(201).json({success :false, message: message})
}else{
const dbPlaceReservation = req.body
PlaceReservation.create(dbPlaceReservation, (err,data)=>{
if(err)
res.status(500).json({success: false, message: err})
else
res.status(201).json({success: true, data: data, message: 'SUCCESSFULY_RESERVED'})
})
}
}
})
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
