Kyle Meade
Kyle Meade

Reputation: 65

Removing all documents in a collection by comparing date index with current date

Problem Summary

I want to have a confident implementation of this, as I really don't know how I would test it. As this functionality really is only relevant at a scale, and for long-term use, but it would make me uncomfortable if I didn't have it.

I have a model in my Node.js/Express/Mongoose(MongoDB) REST APi and it has an index for a date (Not Date.now, a user selected Date). In part of my routes for this model, I want to be able to Query the model based on a different index, but I want to remove all documents in that query where the date index has a date that is before the current date (Date.now).

What I've tried

I came up with a solution though it creates an array of IDs of the documents that should be deleted, and I don't know how to delete by that array of IDs.

// @route  GET api/events/new/:course
// @desc   Find upcoming events based on the course
// @access Private
router.get('/new/:course', auth, async (req, res) => {
    try {
        // Query the events based on the course
        const events = await Event.find({course: req.params.course});

        let finishedEvents = [];
        let validEvents = [];

        // Find & Save the IDs of all events that aren't finished
        events.foreach(event => {
            if (Date.now < event.date) {
                validEvents.push(event);
            } else {
                finishedEvents.push(event.id);
            }
        });

        /** How do I delete 'finishedEvents' without any asynchronously-related issues,
         *  like i'm not sure mapping through 'finishedEvents' and removing them individually
         *  would work. Plus mongoose doesn't even have a 'deleteById' query type like it has
         *  'findById'. Could I just .deleteOne({ id: arrayElement }) ?
         */


        res.json(validEvents);


    } catch (err) {

        console.error(err.messsage);
        res.status(500).send('Server error');

    }
});

I'm expected to return the array of events in 'validEvents' and delete all the documents with an array contained in 'finishedEvents'.

Upvotes: 0

Views: 187

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

You can use .deleteMany() in mongoose.

Sample:

await Event.deleteMany({id: {$in: finishedEvents}});

Or delete by date:

await Event.deleteMany({date: {$gte: Date.now()}});

Upvotes: 1

Related Questions