Reputation: 3580
I have a Node.js function which is inserting an Invitation object into the appropriate collection via MongoDB. The schema says that the email property of the invitation must be unique. I'm using Async/Await, and could use a recommendation on a good pattern to check whether an invitation already exists for that email, whether that invitation is expired, and if so, to delete it and insert the new one.
Here's what I've got so far. It's not deleting expired invitations, and so the update fails. Not sure why.
const oldInvitation = await Invitation.findOne({ email, companyCode });
if (oldInvitation && new Date() < oldInvitation.auth.expires) {
responseObj.email ='User has already been invited to join this company';
continue;
}
if (oldInvitation && new Date() > oldInvitation.auth.expires) {
const clearInvitation = await Invitation.remove({email});
}
const invitation = new Invitation({
email,
company,
companyCode,
inviter,
invitedRole
});
try { const newInvitation = await invitation.save();}
catch (e) {
console.log('error saving invitation ', e.message);
responseObj.email = e.message;
continue;
}
Upvotes: 0
Views: 451
Reputation: 3264
you need a better way to compare dates. like moment or if ldInvitation.auth.expires is a time-stamp then you can use new Date.now() to compare. that is your problem i guess.
Upvotes: 1