I'm working on a hotel room reservation system. Following are attributes in Room model.
rId: String,
allocation: [{
date: Number, // 210403 == 2021-04-03
slots: [{
type: mongoose.Schema.Types.Mixed,
ref: 'reservation',
maxItems: 48
}]
}],
_active: Boolean
This "slots" is an array with 48 items(30mins time slots).Here I want to update this array with user inputs.As an example if a user wants to reserve a time between 2.30 - 3.30 i want to update that two slots in array to "reserved". Following code is the controller for reservation
reservation
.save(reservation) //Save reservation data
.then((data) => { // Update room slots
var dt = req.body.checkInDate.substr(0, 10); // extract date from user input
var tm = req.body.checkInDate.substr(11, 5); // extract time
dt = dt.replace(/-/g, ''); // 210403 == 2021-04-03
tm = tm.replace(/:/g, '.');
console.log(tm)
console.log(dt)
Room.findOneAndUpdate({ rId: rId }, { //Update time slot
$push: {
allocation: [{
date: dt,
slots: [{ tm }]
}]
}
})
Above code is not working. Can someone help me with this?
Demo - https://mongoplayground.net/p/bn1lJpZzhUT
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
db.collection.update(
{ rId: 1, "allocation.date": 20190701 },
{ $push: { "allocation.$[a].slots": { a: 1, b: 2 } } },
{ arrayFilters: [ { "a.date": 20190701 } ]}
)