I want to expire documents in mongodb I found out that documents can expire and get deleted from the db if they have something like this in their schema:
{
name: string,
createdAt:{ type: Date,
expires: '1d',
default: Date.now()
}
}
1d means all docs will expire in one day, I want documents to have different expiry periods, How can I get this value from the POST request body, if my body is
{ 'name': 'pius', 'expiry': '3d'}
And having my schema changed to
{
name: string,
createdAt:{ type: Date,
expires: string,
default: Date.now()
}
}
Can I pass the expires string value via a request if yes how can it be done
CodePudding user response:
TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time. Data expiration is useful for certain types of information like machine generated event data, logs, and session information that only need to persist in a database for a finite amount of time.
db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 } )
You can check this link for more details.
CodePudding user response:
Use a framework or the native nodejs http module. Parse the request and get the body of it transformed (or transforming) in JSON. Access de property and call the insert operation of the mongodb. In that case, the document will expire in the date specified on the request.
See express req.body documentation and router declaration to get more details.
