skip to Main Content

I created a time-series collection using MongoDB database, and I expected the data to be automatically deleted after 2 minutes, but it did not happen. I checked the database and found that the data still exists.

I created a time-series collection using MongoDB database and I need to delete the data in the nonce field after 2 minutes. I created it using MongoDB Compass, and my parameters are as follows:

enter image description here

However, when I insert data using mongoose in node.js, the data is not deleted after 2 minutes.

Here is the code I am using:

const nonceSchema = new mongoose.Schema({
    nonce: String,
    ts: Date,
})

const nonceModel = mongoose.model('nonce', nonceSchema,'nonce');

await nonceModel.create({
        nonce: nonce,
        ts: new Date(),
    });

This code correctly inserts data, but the data is not automatically deleted.

[{
  "ts": {
    "$date": "2023-04-29T06:28:21.345Z"
  },
  "nonce": "R8tYOm15zEu1BupI",
  "_id": {
    "$oid": "644cb90554447c607a4a5a37"
  },
  "__v": 0
},{
  "ts": {
    "$date": "2023-04-29T06:28:47.098Z"
  },
  "nonce": "fFHGD8h6LwUDFIWo",
  "_id": {
    "$oid": "644cb91f54447c607a4a5a3b"
  },
  "__v": 0
}]

What should I do? Thank you for your help.

2

Answers


  1. Chosen as BEST ANSWER

    Solution: Create nonce as a regular collection instead of a time series and add the following code to the JavaScript:

    const nonceSchema = new mongoose.Schema({
        nonce: String,
        ts: Date,
    })
    // add this code
    nonceSchema.index({ ts: 1 }, { expireAfterSeconds: 120 });
    const nonceModel = mongoose.model('nonce', nonceSchema,'nonce');
    
    await nonceModel.create({
            nonce: nonce,
            ts: new Date(),
        });
    

  2. You need to create the TTL index before you insert data into the collection. If you create the TTL index after inserting data, the existing data will not be deleted automatically based on the TTL index.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search