In my Node.js app, I'm trying to add a TTL index to a date field in a MongoDB collecion to make it expire at a specified date.
The application gets the current date through new Date()
, converts it to miliseconds through the getTime()
method, adds a number of miliseconds specified by the user (expiration time), and converts the result back to Date format through setTime()
. The result is saved to a field named expireAt
in a JSON object that is eventually inserted into a MongoDB collection.
The result looks fine, as it accurately represents the date according to UTC timezone adjusted to the expiration time that was added to the current date. For example: expireAt: "2017-05-14T13:59:01.998Z"
, which was inserted at approximately 13:00 UTC with a 1 hour expiration time.
To add the TTL index, I added the following line in my Node application:
collection.createIndex({"expireAt": 1}, {expireAfterSeconds: 0, name: "_exp"});
This, however, gave me a MongoError: Values in the index key pattern cannot be 0
error and no index was created, so I switched to:
collection.createIndex({"expireAt": 1}, {expireAfterSeconds: 1, name: "_exp"});
This time, and index was created when I ran it, as I could see using MongoDB Compass
I then proceeded to insert documents with a expireAt
field, such as the one explained above with expireAt: "2017-05-14T13:59:01.998Z"
. However, it's been nearly an hour since the document should have expired and it has not. In addition, the image above shows that the TTL index has 0 usage, which suggests that for some reason the new documents inserted are not making use of that index despite having the expireAt
field.
Moreover, MongoDB compass displays the content of the expireAt
field as type string instead of the specific BSON date type. However, I'm not sure if this is only a Compass thing since it doesn't let me edit the field type to anything other than String, Object or Array.
Is there anything I could be missing, or has anyone ever ran into a similar issue and found a soultion? I tried to look for a solution in similar questions without success.
via Jorge Sasiain
No comments:
Post a Comment