0

Here's a simple Schema how do I delete the document after either a day or 5 seconds?

import mongoose from 'mongoose';

const schema = new mongoose.Schema({
    id: {type: String, required: true},//yelp id
    userId: {type: mongoose.Schema.Types.ObjectId, required: true}
});

Ideas I've tried some delete after a minute nothing deletes in a day.

// schema.index({createdAt: 1},{expireAfterSeconds: 3600});// doesnt work
// schema.index({"expires": 1}, {expireAfterSeconds: 5});
// schema.index({ first: 1, last: -1});
 // schema.index({ createdAt: { type: Date, expires: 1 }});
 // schema.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 })
// schema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 0 } )

I'm hoping for a short sweet mongoose solution nothing too complicated.

user10109
  • 121
  • 1
  • 3
  • 9
  • Did you tryed this question? https://stackoverflow.com/questions/5809788/how-do-i-remove-documents-using-node-js-mongoose#answer-10266789 – Elad Dec 05 '17 at 22:12
  • 1
    It has to be deleted after a certain amount of time I've spent hours looking through questions haven't found an answer that works because usually it just deletes around one minute. – user10109 Dec 05 '17 at 22:16
  • Document does not need to be deleted if you don't tell him to. you have to separate your question to 2 parts, one is to fire a function every X minutes/hours/days, and second part, is to delete the document.for now you know how to do the second part. implementation of the first part is depends on how your application work. – Elad Dec 05 '17 at 22:21
  • I don't understand what you're trying to convey, can you write down what you're talking about? – user10109 Dec 05 '17 at 22:40
  • Do you want to setup a time to live on a per document basis or on a per collection basis (for all documents in a collection the same TTL)? – kentor Dec 05 '17 at 23:39
  • @kentor At a per document basis. Basically, I want to delete the document after 24 hours or by 2 am Eastern Time. – user10109 Dec 05 '17 at 23:45
  • Have you seen this? https://stackoverflow.com/a/14597622/5774004 – Sreeragh A R Dec 06 '17 at 04:09
  • Yes, it doesn't work it removes the document around 1 minute even if you set the expire longer. – user10109 Dec 06 '17 at 04:27

1 Answers1

0

You can use TTL index to delete data automatically after 5 seconds.

db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 5 } )

Sohan.Choudhury
  • 201
  • 2
  • 4
  • Ok but I need to do this in node not mongoshell and explain specifically what db and eventlog are here for instance is db= mongoose and eventlog= collection('name')?? I'm going to run my database on either localhost or mongolab – user10109 Dec 06 '17 at 04:24