Home > front end >  How do I make my document automatically delete? With Mongoose in javascript
How do I make my document automatically delete? With Mongoose in javascript

Time:10-10

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({
      ...
    });
  }
});

CodePudding user response:

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.

  • Related