0

I use mongoose this is my schema:

const ShortUrlModel = mongoose.model(
  'ShortUrl',
  new mongoose.Schema({
    original_url: String,
    hash: String,
    expires_at: { type: Date, expires: 5000 },
  }),
);

I put expires in 5 secound for test, but it does not work

i wanna expire in 10 days.

when posting to my server to add a url

fastify.post('/new', async (request, reply) => {
  let original_url = request.body.url;
  let hash = request.body.hash;
  const today = new Date();
  const expires_at = new Date();
  expires_at.setDate(today.getDate() + 10);

  let short = await ShortUrlModel.findOne({ hash });

  if (short) {
    ...
  } else {
    const newShortener = new ShortUrlModel({
      original_url,
      hash,
      expires_at,
    });

    let saveUrl = await newShortener.save();

    console.log(saveUrl);
    reply.send({
      ...
    });
  }
});

1 Answer 1

1

The field is expireAfterSeconds

const ShortUrlModel = mongoose.model(
  'ShortUrl',
  new mongoose.Schema({
    original_url: String,
    hash: String,
  }, {
    expireAfterSeconds: 5000
  }),
);

Also note if you change the number of seconds, you need to delete the index and recreate the index. Change does not happen just because you change the seconds in your schema declaration.

More on changing of expire here

Note 2: Expiration of documents in Mongodb does not happen instantly (e.g. exactly 5 seconds). This is stated in the mongodb documentation.

The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time that a document expires and the time that MongoDB removes the document from the database.

Sign up to request clarification or add additional context in comments.

1 Comment

You could manually adjust the expire time on the index without dropping it if you'd prefer: mongodb.com/docs/manual/reference/command/collMod/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.