I am making a booking application, here when I want to create the booking, I must put a condition that the user cannot make a reservation of the room if it is already reserved for another one
So here is my code, it does not work it gives me this error:
throw new Error(Invalid value ${logger.inspect(val)}
);
^
Error: Invalid value { from: { '$between': [Array] } }
I think the error is in the format but I don't know how to write it correctly
this is booking code :
router.route('/BookingRoom').post(async(req, res) => {
const BookingRoom = new Booking({
room_id : req.body.room_id,
user_id : req.body.user_id,
endTime : req.body.endTime,
startTime : req.body.startTime,
});
const start = await Booking.findOne({where:{startTime :new Date(req.body.startTime)}})
const end = await Booking.findOne({where:{endTime :new Date(req.body.endTime)}})
const book = await Booking.findAll({where: {
$or: [{
from: {
$between: [ start, end]
}
}, {
to: {
$between: [start, end]
}
}] ,room_id :req.body.room_id }});
if(!book){
BookingRoom.save()
.then(Booking => {
res.json(Booking);
console.log('the room ' req.body.room_id ' has been successfully reserved for you')
}
)
.catch(err => res.status(400).send((err).toString()));
}
else{
console.log("err");
return res.send(500, 'Booking exist already at this time');
}
});
CodePudding user response:
I think the query should be like this.
const book = await Booking.findAll({
where: {
startTime: {
[Op.between]: [new Date(start.startTime), new Date(end.endTime)],
},
room_id: req.body.room_id,
},
})
because start
and end
variables are instances of Booking
.
CodePudding user response:
Ichange it like that , no error it works but it's always send me: "booking exist already at this time "
const start = await Booking.findOne({where:{startTime :new Date(req.body.startTime)}})
const end = await Booking.findOne({where:{endTime :new Date(req.body.endTime)}})
const book = await Booking.findAll({where: {
startTime: { [Op.and]: {
[Op.gte]: start,
[Op.lte]: end
}
//[Op.between]: [new Date(start.startTime), new Date(end.endTime)],
},room_id :req.body.room_id }});
if(!book){
BookingRoom.save()
.then(Booking => {
res.json(Booking);
console.log('the room ' req.body.room_id ' has been successfully reserved for you')
}
)
.catch(err => res.status(400).send((err).toString()));
}
else{
console.log("err");
return res.send(500, 'Booking exist already at this time');
}```
CodePudding user response:
The problem lies in your variables.
Accordingly to
const start = await Booking.findOne({where:{startTime :new Date(req.body.startTime)}})
const end = await Booking.findOne({where:{endTime :new Date(req.body.endTime)}})
Your variables are instances of Booking
model not Date
.
Firstly you have to retrieve dates from start
and end
variables.
const { startTime } = start;
const { endTime } = end;
Then use it inside between
...
$between: [startTime, endTime]
...