Boyan Hristov
Boyan Hristov

Reputation: 1102

Deleting nested object after time - MongoDB + Node.js

I found information about MongoDB's TTL, which unfortunately only works on whole documents. I want to be able to delete user's notifications after some time (2 weeks) on my Node.js server. As you can imagine, the notifications are an array of objects as a field in the user's MongoDB Model, so that I can get them on login without further requests. So if I have something like this:

notifications: [{
        notifType: String,
        story: String,
        seen: Boolean,
        createdTime: Date,
        from: {
            name: String,
            username: String,
            id: mongoose.Schema.ObjectId
        }
    }]

How do I delete a notification after 2 weeks, counting from createdTime?

Upvotes: 0

Views: 540

Answers (2)

Anantha Sharma
Anantha Sharma

Reputation: 10108

how does the default TTL implementation not do what you are expecting? Say your createdTime field has 2015-02-22:10:20 as the value and using the TTL feature you can

db.notifications.ensureIndex( { "createdTime": 1 }, { expireAfterSeconds: 3600 } )

this will clear the value after 2 hours, Similarly you can set it to be 2 weeks. Unless your requirement is that each record has a different expiry for notifications the default implementation should do perfectly.

You could also write some code as part of the solution which deletes the records periodically, say at the beginning of each day or at the insertion of each record (the latter is not recommended).

Upvotes: 0

Randy Kamradt Sr.
Randy Kamradt Sr.

Reputation: 464

If culling them in a periodic batch process is not feasible, I would make the check as part of whatever code gets the document. You may have notifications longer than two weeks in the database, but assuming you have a single place where a 'get' takes place, you could do the check there and guarantee that no document with a stale notification is returned untrimmed.

Upvotes: 1

Related Questions