how to delete document from mongoose after certain time

Viewed 410

so I need to automatically delete document from collection after 2 minutes if paramter isValidatedis set to false, now I made this:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;
const Model = mongoose.model;

const UserSchema = new Schema(
  {
    email: {
      type: String,
    },
    username: { type: String },
    createdAt: {
      type: Date,
      default: Date.now,
    },
    points: {
      type: Number,
      default: 0,
    },
    validation: {
      type: String,
    },
    isValidated: {
      type: Boolean,
      default: false,
    },
    roles: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Role",
      },
    ],
    password: {
      type: String,
    },
  },
  { collection: "users" }
);

UserSchema.index(
  { createdAt: 1 },
  {
    expireAfterSeconds: 120,
    partialFilterExpression: { isValidated: false },
  }
);

const User = Model("User", UserSchema);

module.exports = User;

But this .index is not working, and I don't know why.

1 Answers

For this to work you have to create the indexing on the field createdAt first and then you have to create TTL indexes so that MongoDB can use to automatically remove documents from a collection after a certain amount of time.

db.collectionName.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 120 } )

You should check here for more details.

Or, Just try adding this to the schema, but this will just delete the documents in 2 minutes(This will help you understand if there is an issue with Conditional delete or not, follow the above link):

const mongoose = require("mongoose");

const Schema = mongoose.Schema;
const Model = mongoose.model;

const UserSchema = new Schema(
  {
    email: {
      type: String,
    },
    username: { type: String },
    createdAt: {
      type: Date,
      default: Date.now,
      expires: 120
    },
    points: {
      type: Number,
      default: 0,
    },
    validation: {
      type: String,
    },
    isValidated: {
      type: Boolean,
      default: false,
    },
    roles: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Role",
      },
    ],
    password: {
      type: String,
    },
  },
  { collection: "users" }
);

const User = Model("User", UserSchema);

module.exports = User;

Related