Update document that contain TTL with reseting the TTL

I’m trying to create a document, that last 120 seconds, and as soon as i call this method i want the TTL to restart.

At the moment i can"t update my document, after 120 sc … the document get deleted and re-created instead of being always updated.

There is my collection :

LaptopConnections = new Mongo.Collection('laptopConnection');

let LaptopConnectionSchema = new SimpleSchema({
  creationDate: {
    type: Date,
    label: "Date when the laptop was created",
    defaultValue: Date.now
  },
 
  "state.date": {
    type: Date,
    label: "time when the laptop was updated",
    autoValue: function () {
      return new Date;
    }
  }
}
  , { timestamps: true }
)
LaptopConnections.attachSchema(LaptopConnectionSchema)

And there is my method :

Meteor.startup(() => {
    LapConnections._ensureIndex({ createdAt: 1 }, { expireAfterSeconds: 120 });// Will delete the collection after ~~ two minutes,

});
Meteor.methods({

  create_lapconnection(lap_id) {
    check(lap_id, String);
    if (!LapConnections.findOne({ _id: lap_id })) {
      console.log('workiiing',lap_id)
      LaptopConnections.insert({
        _id: box_id,
        creationDate: Date.now(),
      });
    } else {
      console.log('updated',lap_id)
      LaptopConnections.update({ _id: lap_id }, { upsert: true }, {
        $set: {
          "state.date": Date.now(),
        }
      }
      );

    }
  }
})

There are several issues with your code:

  1. You have a TTL index on createdAt.

  2. You are using creationDate on the insert.

  3. You are using state.date on the update.

  4. You are using the MongoDB library form of the update, but you should be using the Meteor form. For an upsert:

    LaptopConnections.upsert({ _id: lap_id }, {
      $set: {
        "state.date": Date.now(),
      }
    });
    

Your TTL will only apply to the createdAt, but I’m not sure what you expect to happen.

1 Like

I want to have The date of the creation of my document ( don’t want to change it ) and when i do an upsert the state.date get updated + the TTL go back to 0

That sounds like you want the TTL index on "state.date".

Did like you told me unfortunately not working.

Upsert is not working :confused: i can only do an updet

You cannot just change the TTL index if you have already defined it on a collection. You need to either drop and recreate, or use the MongoDB collmod command.

Check the docs for usage:

1 Like