Max Max - 9 months ago 39
Node.js Question

How to set TTL to expire documents using MONK?

I read the MongoDB documentation in order to figure the how to expire a document using the Time To Live property.

The doc says:

To expire data after a specified number of seconds has passed since
the indexed field, create a TTL index on a field that holds values of
BSON date type... For example, the following operation creates an
index on the log_events collection’s createdAt field and specifies the
expireAfterSeconds value of 3600 to set the expiration time to be one
hour after the time specified by createdAt

db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

When adding documents to the log_events collection, set the createdAt
field to the current time:

db.log_events.insert( {
"createdAt": new Date(),
"logEvent": 2,
"logMessage": "Success!"
} )

How do I do that using node Monk?

Nix Nix

Should be:

db.log_events.ensureIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })

Documentation on ensureIndex

Ensures that indexes exist, if it does not it creates it