如何验证会话中的时隙冲突



我有一个Session模型,它有一个日期、一个开始时间和一个结束时间,如下所示//假设会话模型是在同一个文件中定义的const mongoose=需要('mongose'(

const SessionSchema = new mongoose.Schema({
    date: {
        type: Date,
        required: [true, 'Date is required for session']
    },
    start: {
        type: Date,
        required: [true, 'Please specify end time for session']
    },
    end: {
      type: Date,
      required: [true, 'Please specify end time for session']
    },
    owner: { type: Schema.Types.ObjectId, ref: 'User' },
    participants: {
      type: [Schema.Types.ObjectId],
      ref: 'User'
    },
 })
module.exports = mongoose.model('Session', SessionSchema)

在我的"/会话创建";路由,我想在创建会话之前确保所有者在会话时间间隔中没有另一个冲突部分。这意味着新会话的时间间隔应该在所有者的任何其他现有会话的时间区间之外。

我该怎么做?我很困惑我应该如何确保在他们的时间间隔内没有冲突的会议。

这是我的会话创建路线:

post("/create-session", (req, res) => {
     const { date, start, end } = req.body
     
     // Getting the start datetime
     startHours = start.slice(0, 2)
     startMinutes = start.slice(3)
     startDateTime = new Date(date).setHours(startHours, startMinutes)
     // Getting the end datetime
     endHours = end.slice(0, 2)
     endMinutes = end.slice(3)
     endDateTime = new Date(date).setHours(endHours, endMinutes)
     
     // Session owner cannot have 2 time-conflicting sessions
     // Session start time should not in be in the 
         // time interval of already existing sessions, i.e,
     // Session end time should not be within the time interval of already 
         // existing sessions
}

如何确保会话所有者在创建会话期间不能有两个时间冲突的会话?换句话说,如何在创建时验证会话开始时间不在现有会话的时间间隔,并且会话结束时间不在现有会话的间隔内?

您可以查询开始日期小于body.date、结束日期大于body.date的会话,如果存在则返回错误

post("/create-session", (req, res) => {
  const { date, start, end } = req.body
  // Getting the start datetime
  startHours = start.slice(0, 2)
  startMinutes = start.slice(3)
  startDateTime = new Date(date).setHours(startHours, startMinutes)
  // Getting the end datetime
  endHours = end.slice(0, 2)
  endMinutes = end.slice(3)
  endDateTime = new Date(date).setHours(endHours, endMinutes)
  
  const existingSession = await findOne({ $and: [{ startDate: { $lt: startDateTime } }, { endDate: { $gt: startDateTime } }] })
  if (existingSession) return res.status(400).send({err: "not allowed"})
  // Session owner cannot have 2 time-conflicting sessions
  // Session start time should not in be in the 
      // time interval of already existing sessions, i.e,
  // Session end time should not be within the time interval of already 
      // existing sessions
})

相关内容

  • 没有找到相关文章

最新更新