Versions of this question have been asked for many databases but I did not see a version of this question on stackoverflow for MongoDB. We have a users collection in our database, and we are trying to create trial accounts for our website. We have the following user schema:
{
name: 'Joe Smith',
email: '[email protected]',
userTier: { value: 0, label: 'none' }
}
When a user signs up, their userTier
starts at { value: 0, label: 'none' }
, when they verify their email address, userTier
goes to { value: 1, label: 'verified' }
via a route in our Node API:
router.get('/verify-email/:userId/:token', async (req, res) => {
try {
const { userId, token } = req.params;
const emailToken = await EmailVerificationToken.findOne({ token: token });
if (!emailToken) { // bad token, do not verify
return res.redirect(`${frontEndUrl}/verify-email-page/no-token`);
}
const thisUser = await User.findOne({ _id: userId });
if (!thisUser) { // no user found, do not verify
return res.redirect(`${frontEndUrl}/verify-email-page/no-user`);
}
if (thisUser.tier.value > 0) { // if already verified
return res.redirect(`${frontEndUrl}/verify-email-page/already-verified`);
}
// otherwise, verify user
thisUser.tier = { value: 1, label: 'verified' };
thisUser.save(function (err) {
if (err) {
return res.redirect(`${frontEndUrl}/verify-email-page/cant-save-user`);
}
res.redirect(`${frontEndUrl}/verify-email-page/success`);
});
} catch (error) {
res.status(500).json({ statusCode: 500, message: error.message });
}
});
...not a perfect route with the different res.redirect()
s, but it gets the job done. We are now looking for a way to temporarily update the userTier
to { value: 2, label: 'trial' }
for 1-2 weeks, after which the value automatically changes back to { value: 1, label: 'verified' }
. We would prefer a mongo-only approach (perhaps we can set an expiration
field in the user schema that automatically changes the userTier
value when the expiration time is reached), although it seems unlikely that this is possible... How are 1 week trials typically coded up under the hood when using mongo node?
CodePudding user response:
I do not think there is a MongoDB-only way. I suggest that you set a Node.js cron function that would execute every night/morning and would deactivate the expired trials.
const schedule = require('node-schedule');
const job = schedule.scheduleJob('0 1 * * *', function(){
// update the users for whom the trial expired
});
MongoDB in the end is powered by a server that may crash or would restart when the machine restarts anyway. As far I know, there is no such functionality as memorising particular actions in the database server itself.
Instead, you can have a middleware to check if the trial expired.