【发布时间】:2018-05-06 16:22:49
【问题描述】:
我有一个 Node.js 函数,它通过 MongoDB 将 Invitation 对象插入到适当的集合中。该架构表示邀请的电子邮件属性必须是唯一的。我正在使用 Async/Await,并且可以使用关于良好模式的建议来检查该电子邮件的邀请是否已经存在,该邀请是否已过期,如果是,则将其删除并插入新的。
这是我到目前为止所得到的。它不会删除过期的邀请,因此更新失败。不知道为什么。
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;
}
【问题讨论】:
标签: node.js mongodb mongoose async-await