Why is my MongoDB TTL code working in one schema but not in the other-

26 Views Asked by At

So I have the following Schema, I tested it with a 50 second delay and it worked after the second minute (MongoDB 1 minute process interval).

import mongoose from "mongoose";
import "./DamageReport";
import "./Service";

const { Schema } = mongoose;

const carSchema = new Schema({
  licensePlateNumber: { type: String, required: true },
  damageReports: [{ type: Schema.Types.ObjectId, ref: "DamageReport" }],
  serviceHistory: [{ type: Schema.Types.ObjectId, ref: "Service" }],
  createdAt: { type: Date, default: Date.now }, // Add createdAt field
});

// Create a TTL index for the createdAt field with a 30-minute expiration
carSchema.index({ createdAt: 1 }, { expireAfterSeconds: 1800 });

// Define the Car model if it doesn't already exist
const Car = mongoose.models.Car || mongoose.model("Car", carSchema);

export default Car;

I then thought, wow that is easy, so I applied it to another schema.

import mongoose from "mongoose";

const { Schema } = mongoose;

const benzineCountSchema = new Schema(
  {
    name: { type: String, required: true },
    count: {
      type: Number,
      required: true,
      minimum: 0,
      validate: {
        validator: Number.isInteger,
        message: "The count must be a whole number.",
      },
    },
    isRefill: { type: Boolean, default: false },
    createdAt: { type: Date, default: Date.now }, // Add createdAt field
  },
);

benzineCountSchema.index({ createdAt: 1 }, { expireAfterSeconds: 1 });

const BenzineCount =
  mongoose.models.BenzineCount ||
  mongoose.model("BenzineCount", benzineCountSchema);

export default BenzineCount;

The alteration immediately deleted every single previous entry, from months ago, clearing my collection, but none of the new entries will delete.

Can anyone assist me in understanding what is going on?

0

There are 0 best solutions below