Node.js 使用Async/Await的Mongoose:在插入之前验证唯一性

Node.js 使用Async/Await的Mongoose:在插入之前验证唯一性,node.js,mongodb,mongoose,async-await,Node.js,Mongodb,Mongoose,Async Await,我有一个Node.js函数,它通过MongoDB将邀请对象插入到适当的集合中。模式表示邀请的电子邮件属性必须是唯一的。我正在使用Async/Await,可以使用一个良好模式的建议来检查该电子邮件是否已经存在邀请,该邀请是否已过期,如果是,则删除它并插入新的邀请 这是我到目前为止得到的。它没有删除过期的邀请,因此更新失败。不知道为什么 const oldInvitation = await Invitation.findOne({ email, companyCode }); if (oldInv

我有一个Node.js函数,它通过MongoDB将邀请对象插入到适当的集合中。模式表示邀请的电子邮件属性必须是唯一的。我正在使用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;
          }
constoldinvitation=wait Invitation.findOne({email,companyCode});
如果(旧邀请和新日期()oldInvitation.auth.expires){
const clearInvitation=等待邀请。删除({email});
}
const invitation=新邀请({
电子邮件
公司
公司代码,
邀请人,
邀请酒店
});
请尝试{const newInvitation=wait invitation.save();}
捕获(e){
console.log('保存邀请时出错',e.message);
responseObj.email=e.message;
持续
}

您需要一种更好的方法来比较日期。
如果ldInvitation.auth.expires是一个时间戳,则可以使用new Date.now()进行比较。我想这就是你的问题。

我现在这样做有什么问题?@Boris K我不知道oldInvestment.auth.expires的值和类型是什么。它是时间戳是日期对象还是日期字符串?这段代码是否在循环中运行?为什么要使用continue?嘿,Amit,旧的invitation.auth.expires是一个日期对象。代码在循环中运行,因为它正在处理用户发送的邀请数组(我不想发送整个方法,因为它太长了)