What is causing MongoDB to delete documents based on TTL even when the partial filter does not align with the specified option?

I noticed that my partial filter is deleting documents even when the user does not meet the specified requirement. Could it be possible that I am using the partial filter incorrectly?

Thank you for your assistance.


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
    }
);

// Posts from non-premium users will be deleted after 20 seconds
postSchema.index({ createdAt: 1 }, { expireAfterSeconds: 20, partialFilterExpression: { authorPremium: false } });

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

The partial filter should prevent deletion of posts with authorPremium set to true, and only delete if authorPremium is false. Please provide guidance on this matter.

The response from the MongoDB 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 appears that some of the old settings remain when using Mongo command, while some new ones are added. How can I completely remove these old TTL settings during testing to ensure only the desired ones are retained?

Answer №1

Your .index(...) method may not be working because there is an old index already set on the createdAt field, which Mongoose does not automatically drop. To resolve this issue and synchronize the indexes with your schema, you can use the handy Model.syncIndexes function.

If you want to learn more about how the .index() method functions and why .syncIndexes() was introduced, check out this informative article here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to use a jQuery each loop to retrieve the margin of an element

I currently have 7 different elements, each with unique margin-left and margin-top properties set in the CSS file. I am looking to loop through these elements and gather information about their margins. This is what my jQuery code looks like so far: var ...

Tips for concurrently executing multiple requests using axios without waiting for each request to finish

I am looking to send multiple requests using Axios simultaneously, without waiting for each request to finish sequentially. What I aim to achieve is to have the second request process and return even while the first request is still pending. I do not want ...

Issues arise when jQuery functions do not execute as expected within an "if" statement following

Recently, I delved into the realm of AJAX and embarked on a journey to learn its intricacies. Prior to seeking assistance here, I diligently scoured through past queries, such as this, but to no avail. Here is an excerpt from my code: $('.del'). ...

Is there a way to design a side menu navigation bar that reveals items by sliding them out to the right?

Currently, I am attempting to emulate a website as practice since I am relatively new to HTML, CSS, and JavaScript. As part of this exercise, I have designed a navigation bar on the left side (similar to the example provided for food items). The objectiv ...

How to query the entire MongoDB collection with Node.js

I am looking to create a full search functionality in my MongoDB collection using Node.js. How can I modify the SaleModel.find() function to search for a value across the entire collection? Currently, my implementation only searches the 'product_name ...

Sending a large amount of text data from JavaScript to php

What is the most effective method for transferring a lengthy string variable (2000+ characters) from JavaScript to a PHP page, along with additional data, for storage in a database? ...

The most effective method for acquiring an object through inheritance

I'm seeking advice on the best practice for adding behavior to an object received as a JSON object. I have REST services that allow me to define a sort of state machine. The API defines a /sessions resources. When creating a session via POST /sessio ...

The $digest function in Angular's $rootScope

While engrossed in the incredible book, Mastering Web Development in AngularJS, I stumbled upon this code snippet: var Restaurant = function ($q, $rootScope) { var currentOrder; this.takeOrder = function (orderedItems) { currentOrder = { deferred ...

Encountering an issue with the message "chartobject-1.render() Error >> Unable to locate the container DOM element." within a JavaScript function

I have encountered an issue while working with Fusion Charts in my HTML page using JavaScript. When attempting to display two charts simultaneously, I receive an error message that says: "fusioncharts.js:71 Uncaught RuntimeException: #03091456 chartobjec ...

Unable to display an image prior to its upload

I'm facing an issue with changing the image for my second data. It's not updating, but when I try it with the first data, it works fine. I'm unsure why this is happening and would appreciate any help in resolving it. Here is the form where ...

Finding an alternative element in place of _id using elemMatch query in Mongodb

My database is structured like this: { "_id" : ObjectId("5aa7b4b31b93f3230857c303"), "pid" : "5aa7b3d0412f9625484514e3", "likes" : [ { "userid" : "5a9e99b1c85c230edc207c01", "username" : "a" }, ...

What steps should I take to modify the date format to "dd / mm / yy"?

When using 'toISOString ()' in JavaScript, it appears as shown in photo 2. How can I modify this format? Note: I am working with AngularJs. Image 1 is located in list.component.ts Additional documents: Image 1 Image 2 Image 1: formatDate(e) ...

Choose the appropriate data type for the class variable (for example, fArr = Uint32Array)

const functionArray: Function = Uint32Array; new fArr(5); The code snippet above is functioning properly. However, TypeScript is throwing a TS2351 error: "This expression is not constructable. Type 'Function' has no construct signatures". I wo ...

What is the best way to convert an HTML table into an array of objects?

In my Angular Protractor end-to-end (e2e) tests, I need to perform assertions on an HTML fragment similar to the following: <table> <thead> <tr> <th>Name</th> <th>Age</th> ...

Tallying MongoDB aggregation by the key of a nested object

db.artists.insertMany([ { "_id" : 1, "achievements" : {"third_record":true, "second_record": true} }, { "_id" : 3, "achievements" : {"sixth_record" : true, "second_record" : tr ...

Enhance your React application by using a personalized hook that allows you to trigger a function

After creating a custom hook to handle uploads to an AWS S3 bucket, I encountered a small issue. Rather than having the hook execute the logic directly, I decided to create an executable function to return instead. However, I am facing a problem where the ...

Guide for creating a function that accepts an array containing multiple arrays as input

I am working with a function called drawSnake and it is being invoked in the following manner: drawSnake( [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], ] ); How should I format the input for this function? I have attempted using Array<Array<[numb ...

Updates cannot be flushed while React is currently rendering

My goal is to display an alert using sweetalert2 when an error is returned by the API. To achieve this, I check if the error message is not empty in my render method and trigger the alert for the user accordingly. Upon submitting the form, an API call is ...

JavaScript errors due to miscalculations Incorrect calculations lead

Here is the formula I am using in my Javascript code: total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + (rateamount)) * (tax/100)); The values for the variables are as follows: unit = 5, ra ...

Maximizing efficiency when pairing and deleting consecutive database entries - the MongoDB approach

Imagine a scenario where I am creating a blind war game! Users A and B each have a specific number of soldiers. Currently, there are zero DB docs. User A sends 50 soldiers to create a DB doc. User B then follows by sending 62 soldiers! This action resul ...