Im designing a booking system(a place reservation system) and i
m having trouble designing my "Place" Schema. I need to keep track of its availability. Basically i need to find if a certain time frame chose by the user is still available or not. For example the user choses april-may as time of booking. How do i structure it in a way that i can find out if april-may is already taken.
Here`s what i did so far: On my "Place" schema. i added an availability field:
availability: [
{
moveIn: { type: Date },
moveOut: { type: Date },
qty: { type: Number }
}
]
i added quantity to find out how many persons booked on that certain time frame.
This logic would be reserved for a few javascript and mongoose commands, its really up to you but I would recommend something like the following:
Your schema is fine, when a user goes to check out a book, you should first check if it's available.
You can do this by retrieving and unwinding the current dates into their own arrays. This also sorts the dates in order.
var datesIn = {};
Book.aggregate([
{$unwind: '$availability'},
{$sort: {'availability.moveIn': 1}}
], function (err, result) {
datesIn = result;
});
Do this again for dates out:
var datesOut = {};
Book.aggregate([
{$unwind: '$availability'},
{$sort: {'availability.moveOut': 1}}
], function (err, result) {
datesIn = result;
});
The index of each of these arrays now correspond to a checkout out time by a user. If empty, it's available, otherwise, you can use a library like moment.js to compare availability between dates.
Here is a good post about this: Check if one date is between two dates
Finally, once you have found availability, you can push in the new checkout like:
Books.findOneAndUpdate({'Searching criteria goes here'}, {
$push : {
availability : {
"moveIn": firstDate,
"moveOut": secondDate,
"qty": quantityVal
}
}
});
This should append to the availability
array in your document.
Im sure you've heard of not re-inventing the wheel, there are some good libraries out there for things like this, here's one I found:
https://www.npmjs.com/package/availability-schedule
it seems to have an isAvailable (startDate, endDate)
function. :)