0

I set expiry time to 24 hours, but the documents expire after around 5-10 minutes (I haven't timed it exactly). What am I doing wrong? My schema:

const collectionSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  name: {
    type: String,
    maxLength: 30,
    required: true
  },
  entries: [{ type: mongoose.Schema.Types.ObjectId, ref: "Entry" }],
  expireAt: { type: Date, expires: 60 * 60 * 24 }
});

In the post route, I conditionally set the date so that inlogged clients get data persistence.

router.post("/", auth, async (req, res) => {
  let date = null;
  if (!req.user) {
    date = new Date();
  }
  try {
    const collection = {
      userId: req.body.userId,
      name: req.body.name,
      expireAt: date
    };
    const newCollection = await Collection.create(collection);
    res.send(newCollection);
  } catch (error) {
    res.send(error.message);
  }
});

I thought I had a time-zone problem, but when I check the time stamp in MongoDB compass, it matches my time-zone. What am I doing wrong?

Brian Embry
  • 71
  • 2
  • 7

1 Answers1

1

I tested this:

var TestSchema = new Schema({
  name: String,
  createdAt: { type: Date, expires: '2m', default: Date.now }
});

Documents ware deleted after the second minute and I also confirmed that the TTL index was properly created (as a background one by default) with TTL of 120 seconds.

Try that time format and see if that works for you.

Also note that any expected changes to the index via your mongo schema would not be reflected until you manually remove the previous index and start your app to auto-create the new one.

MongoDB version: 3.6.5

Akrion
  • 18,117
  • 1
  • 34
  • 54
  • That seems to have worked. All I did was change the name of the key from 'expiresAt' to 'createdAt'. I guess that name matters. – Brian Embry Sep 30 '18 at 19:18
  • Awesome. If this reply has helped you please consider marking it as the answer so others can find it easier. Thanks! – Akrion Sep 30 '18 at 19:33