简体   繁体   中英

Hello , I want to remove new users from mongoDB atlas within 2 minutes if they do not verify their phone number , I think TTL is the way

Document Schema

1个

this is my User schema and the isVerified field is being saved to the DB with the initial value if false the process is the user enters his phone number and then i send a verification token via SMS for the phone number and save both token and the number in the DB, and then when the user enters the verification token he has received i patch the isVerified field to true . now i want to remove every document that does not turn isVerified to true within 2 minutes of the document creation. i have seen a few code examples but to be honest i dont know how to or where to implement this feature, should it be in the schema or in the document creation process?

since i dont know where to start or how to start i have not tried it yet

MongoDB supports TTL Indexes So I'd suggest the following

  1. In your schema add an optional field verificationTimeout . For each newly created user set this value to the current timestamp
  2. Create a TLL index on this field with an expireAfterSeconds of your own choice (btw 2 minutes is really short, I'd suggest like 15 minutes or so...)
  3. Once the user is verified, remove the verificationTimeout field from the document

Alternatively, you can also set the verificationTimeout to a timestamp where you want your unverified user to be removed and use the expireAfterSeconds: 1 to remove the user at set defined timestamp.

So, if the user didn't verify within the given timeslot, the mongodb server will invalidate the document and remove it from the collection. But as specified in the docs, documents won't be invalidated if the don't contain the specified field. So if you remove the verificationTimeout upon verification, the user won't be removed from the collection.

And the nice thing about this: You don't need to care about removing unverfied users in your own code. The only thing you need to do is create the index and set/remove the value. Ie no extra worker that scans through the elements and checks if they already expired...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM