Let's take the following example:
I have two mongoDb
collections named user
and products
. A user can add unlimited products, but each product expires in 5 days and it has to be dynamically removed from the db when it expires.
user.js
const UserSchema = mongoose.Schema(
{
username: { type: String },
email: { type: String },
timezone: { type: String },
products: [{ type: Schema.Types.ObjectId, ref: 'Products' }]
}
)
export default mongoose.model('User', UserSchema);
products.js
var RunSchema = mongoose.Schema(
{
name: { type: String },
completedAt: { type: Date }
}
)
export default mongoose.model('Run', RunSchema);
Is there another way of doing this in nodejs rather than having one cron job
which runs every day and checks all documents from the products
collection?
I'm thinking about a solution where a each user can have a cron job that starts once they add a product...
It is too late answer the question even though , I would like to give alternative operation with minimal operation and without Cron Job
If you want remove product document after creation of 5 day's interval then you can achieve with 2 line of code in model itself. You have add one property i.e(expireAt) in model and pass the interval to that property with help of moment npm library
var RunSchema = mongoose.Schema(
{
name: { type: String },
completedAt: { type: Date },
expireAt: {
type: Date,
default: moment(new Date()).add("5", "days"),
expires: 432000000
}
}
)
export default mongoose.model('Run', RunSchema);
after creation of product document date and time . it will automatically remove document from collection of every 5 days of interval.