Reputation: 67
I have document:
const User = mongoose.model('User', {
age: Number,
city: String,
history: [new mongoose.Schema({
id: String,
createdAt: {
type: Date,
default: Date.now(),
index: {
expires: 60 * 60 * 5
}
}
})]
});
In the field 'history' will be stored IDs with whom User chatting last for 5 hours. After 5 hours one element from field 'history' will be deleted (which expired). When I create user like this:
let user = new User({
age: 20,
city: 'SPb',
history: [
{
id: 'asd',
createdAt: new Date()
}
]
});
user.save()
It creates user document but after 5 hours it deletes the whole document, instead of deleting element from array :(
Upvotes: 1
Views: 557
Reputation: 10918
That cannot be done with a TTL index. See the documentation which states:
TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time.
You will need to either write that cleanup logic yourself or model the elements that shall be deleted as separate documents which could then be cleaned up by a TTL index.
Upvotes: 2