1

I'm using the expires field in a mongoose schema in order to set expiration on a given field. For instance:

var Crumbs = new Schema({
    ...
    timestamp: {
      type: Date,
      expires: 3600,
      required: true
    },
    ...
});

The effect is the expected one and the following index is created at MongoDB if the index doesn't previously exist:

> db.crumbs.getIndexes()
[
    ...
    {
        "v" : 2,
        "key" : {
            "timestamp" : 1
        },
        "name" : "timestamp_1",
        "ns" : "mydb.crumbs",
        "expireAfterSeconds" : 36000,
        "background" : true
    }
]

However, if the index previously exists it is not created. For instance, if I change to expires: 360 in my code and I re-run my program, "expireAfterSeconds" at MongoDB keeps being 36000.

Is there any way to force the index to use the value defined in the schema, even if the index already exists?

fgalan
  • 11,732
  • 9
  • 46
  • 89

2 Answers2

1

You cannot do it from schema definition.

The best way is to drop index directly in the db.

Alternatively, drop it from the script. E.g.

mongoose.connections[0].collections("collectionname")
.dropIndex("propertyName",callback)
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
0

Thanks to Alex Blex hint, I have finally solved this. First droping the index, then recreating with the new expiration value:

mongoose.connections[0].collections.crumbs.dropIndex({timestamp: 1}, function (error) {
    if (error) {
        // This happens typically if the index doesn't exist but it doesn't hurt anyway
    }
    mongoose.connections[0].collections.crumbs.ensureIndex({timestamp: 1}, {expireAfterSeconds: 360});
});
fgalan
  • 11,732
  • 9
  • 46
  • 89
  • 1
    There is no need to create index manually. Mongoose should create one from the schema, if it doesn't exists. – Alex Blex May 15 '18 at 16:09