Search code examples
javascriptmongodbmongoosemongodb-querymongoose-schema

why is mongoose TTL deleting document, even when partial filter does not match the option


my partial filter is deleting document, but user is not matching that requirement, am I using partial filter incorectly?

Thanks


const postSchema = new mongoose.Schema(
    {
        title: { type: String },
        description: { type: String },
        image: { type: String },
        price: { type: String },
        location: { type: String },
        image: { type: Array },
        author: {
            type: String,
            ref: 'User'
        },
        authorPremium: {
            type: Boolean,
            default: true,
            index:true
        },
        reported: {
            type: Boolean,
            default: false
        },
        reportClear: {
            type: Boolean,
            default: false
        }
    },
    {
        timestamps: true
    }
);

// users who are not premium will have posts deleted after 20 seconds
postSchema.index({ createdAt: 1 }, { expireAfterSeconds: 20, partialFilterExpression: { authorPremium: false } });

module.exports = mongoose.model('Post', postSchema);

partial filer should not allow the authorPremium which is true to be deleted, but only delete is authorPremium is false... please advise.

return from mongo index

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.posts"
        },
        {
                "v" : 2,
                "key" : {
                        "createdAt" : 1
                },
                "name" : "createdAt_1",
                "ns" : "test.posts",
                "expireAfterSeconds" : 120,
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "authorPremium" : 1
                },
                "name" : "authorPremium_1",
                "ns" : "test.posts",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "timestamps" : 1
                },
                "name" : "timestamps_1",
                "ns" : "test.posts",
                "expireAfterSeconds" : 20,
                "background" : true
        }
]

it seems when I use mongo cmd some of my old setting remained.. and some new? So how can I completly clear these old ttl settings when I am testing and ensure only the ones I want are there?


Solution

  • It looks like your .index(...) does not work because you already have old index on createdAt field and mongoose won't drop the old one. To synchronize the indexes with your schema you can use Model.syncIndexes

    More on how .index() works and why .syncIndexes() was introduced can be found here.