Reputation: 599
I'm using MongoDB, Nodejs, etc...
I have an Activity collection about my user activities "Add new project", "Update project", "Delete project", etc, but I don't want that activity permanent on my database, I want that to expire in 30 days after created and added do user dashboard, but I don't now how to do...Hope you can help me! Thank you!
Here's my Activity Schema:
let mongoose = require("mongoose");
let activitySchema = new mongoose.Schema({
activity: String,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
created: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Activity', activitySchema);
Here's my server side:
(this is what send all user activity to dashboard)
//Render User Activity
exports.render_user_activity = (req, res) => {
let userid = req.user._id;
User.findById(userid)
.exec((err, user) => {
if (err) {
console.log(err);
}
Activity.find({ user: user })
.exec((err, activities) => {
if (err) {
console.log(err);
}
res.send(activities);
});
});
};
I've read that I can user .createIndex but I don't know how or if it's the best solution.. Thank you!
Upvotes: 1
Views: 4536
Reputation: 3424
You can for sure use TTL (Time to Live) index in MongoDB. With this TTL you can remove any document after certain amount of time is expired or at a particular date and time in calendar.
As per your question you want to expire each document after 30 days of creation.
You already have a created
field just create an index around it.
let activitySchema = new mongoose.Schema({
.
.
.
.
}, {timestamps: true});
activitySchema.index({createdAt: 1},{expireAfterSeconds: 2592000});
30 days = 2592000 seconds
Upvotes: 4