I have a mongoose Schema which looks like this:
const USERS_DATA = new Schema({ _id: Number, name: String, img: String, date: Date, phone: String, article: String, createdAt: { type: Date, required: true, default: Date.now, index: { expires: '3d' } } }, { collection: "users", _id: false, }
);
I need to push data to this schema.
const User = mongoose.model("users", USERS_DATA); function pushToDB() { const newUser = new User({ name: INPUT.name, img: INPUT.img, date: INPUT.date, phone: INPUT.phone, article: INPUT.article, }); newUser.save(function (err) { mongoose.disconnect(); if (err) return console.log(err); });
}
This data have to be deleted after 3 days when it was pushed to database. How to implement it in node.js? I found it really confusing and tried lots of code. Any answers are appreciated! Thanks
P.S. I use mongoDb Atlas
Answer
You should separate the process to push the data into the database from the process to delete it after 3 days. You have already the first part :).
For the second part, you can write a function deleteOldDocument
. This function will query for documents in DB that are created for 3 days or more, and delete them. Then, you can run this function periodically, 1 time per day for example.
The pseudo-code, in case you need it :
async function deleteOldDocument() { const 3DaysAgo = ...; // here you can subtract 3 days from now to obtain the value // search for documents that are created from 3 days or more, using $lt operator const documentToDelete = await User.find({"created_at" : {$lt : 3DaysAgo }}); // delete documents from database ..... // recall the function after 1 days, you can change the frequence setTimeOut(async function() { await deleteOldDocument(); }), 86400); } // call deleteOldDocument to start the loop deleteOldDocument();