Ask Your Question
3

How do you configure NodeJS to automatically delete a MongoDB document if the associated email address remains unconfirmed?

asked 2023-02-06 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-12-04 21:00:00 +0000

devzero gravatar image

First, you would need to add a field to the MongoDB document that indicates whether the email address has been confirmed or not. For example, you could add a field called "confirmed" with a boolean value set to false by default.

Then, you could set up a cron job to periodically check for documents with the "confirmed" field set to false and that have been in the database for a certain amount of time (e.g. 24 hours). You could use a package like node-cron to run the cron job at regular intervals.

Once the job finds an unconfirmed document that has been in the database for the specified amount of time, you can use MongoDB's native node.js driver or an ODM like Mongoose to delete the document.

Here's some example code to accomplish this:

const cron = require('node-cron');
const MongoClient = require('mongodb').MongoClient;

// Connect to MongoDB
MongoClient.connect('mongodb://localhost:27017', function(err, client) {
  if (err) throw err;

  const db = client.db('mydatabase');
  const collection = db.collection('mycollection');

  // Run cron job every hour
  cron.schedule('0 * * * *', function() {
    // Find unconfirmed documents that have been in the database for at least 24 hours
    const cutoffDate = new Date(Date.now() - 24 * 60 * 60 * 1000); // 24 hours in milliseconds
    collection.find({ confirmed: false, createdAt: { $lt: cutoffDate } }).toArray(function(err, docs) {
      if (err) throw err;

      // Delete unconfirmed documents
      docs.forEach(function(doc) {
        collection.deleteOne({ _id: doc._id }, function(err, result) {
          if (err) throw err;
          console.log(`Deleted document with email address ${doc.email}`);
        });
      });
    });
  });
});

This example code runs the cron job every hour and finds any documents in the "mycollection" collection that have the "confirmed" field set to false and a "createdAt" field that is older than 24 hours. It then deletes each of these documents and logs a message indicating which email address was deleted.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-06 11:00:00 +0000

Seen: 10 times

Last updated: Dec 04 '22