Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

308
Visualizações
Automatically delete a document after date expired in MongoDB and Node js?

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
        });
    }
}
about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Santiago Gelvez Relatório

0

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
})
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda