Mongoose. Set time to live to the specific field

graver Source

I have document:

const User = mongoose.model('User', {
    age: Number,
    city: String,
    history: [new mongoose.Schema({
        id: String,
        createdAt: {
            type: Date,
            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()

It creates user document but after 5 hours it deletes the whole document, instead of deleting element from array :(



answered 2 weeks ago dnickless #1

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.

comments powered by Disqus