skip to Main Content

I have an appointment booking app and I want the booking detail will delete after the booked date expired. How can I achieve that?

I tried it with node-scheduler but does not work. and its a simple API with Crud Operations

I tried to call Scheduler in index.js when server starting

Here is my Code:
//Scheduler

import nodeSchedule from "node-schedule";
import AppointsModel from "../models/AppointsModel.js";

const Scheduler = () => {
  const currentDate = new Date();
  const currentTime = currentDate.getTime();

  const expiredAppoints = AppointsModel.find({
    date: {
      $lte: currentDate,
    },
    time: {
      $lte: currentTime,
    },
  });
  console.log(expiredAppoints);

  expiredAppoints.then((appoints) => {
    appoints.forEach((appoint) => {
      AppointsModel.findByIdAndRemove(appoint._id);
    });
  }
  );
};
export default Scheduler;

//Controller
import AppointsModel from './../models/AppointsModel.js';
import Scheduler from '../middleware/Scheduler.js';

export const CreateAppoint = async (req, res) => {
    try {
       //create a new appointment for react native app
         const newAppoint = new AppointsModel({
            name: req.body.name,
            doctor: req.body.doctor,
            date: req.body.date,
            time: req.body.time,

         })
        // don't save the appoint if there is already one with the same time
        const appoint = await AppointsModel.findOne({ time: req.body.time, date: req.body.date, doctor: req.body.doctor, name: req.body.name });
        if (appoint) {
            res.status(400).json({
                message: "Appointment already exists"
            })
        } else {
            await newAppoint.save();
            res.status(201).json({
                message: "Appointment created successfully"
            })
        }

       
       
    } catch (e) {
        res.status(400).json({
            success: false,
            error: e
        });
    }
}
export const GetAppoints = async (req, res) => {
    try{
        const appoints = await AppointsModel.find();
        res.status(200).json({
             appoints

        })
       
    }
    catch(error){
        res.status(500).send(error);
    }
}

export const DeleteAppoint = async (req, res) => {
    try {
        const appoint = await AppointsModel.findByIdAndDelete(req.params.id);
        res.status(200).send({ message: 'Appointment deleted successfully' });
    } catch (e) {
        res.status(400).json({
            success: false,
            error: e
        });
    }
}

export const UpdateAppoint = async (req, res) => {
    try {
        const appoint = await AppointsModel.findByIdAndUpdate(req.params.id, req.body);
        res.status(200).send({ message: 'Appointment updated successfully' });
    } catch (e) {
        res.status(400).json({
            success: false,
            error: e
        });
    }
}

2

Answers


  1. you can do with TTL

    • TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time.

    try this article https://dev.to/lironer/delete-expired-documents-automatically-with-mongodb-ttl-index-l44

    Login or Signup to reply.
  2. Add this inside of your model. It will create TTL index in your database:

    expireAt: { type: Date, expires: 3600 }
    

    It will delete a document after 3600 seconds

    Then just add expireAt key and your time as a value from which the countdown will start:

    const newAppoint = new AppointsModel({
      name: req.body.name,
      doctor: req.body.doctor,
      date: req.body.date,
      time: req.body.time,
      expireAt: new Date() // or any time you want
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search