【问题标题】:Mongoose with Async/Await: validating uniques before insertingMongoose with Async/Await:在插入之前验证唯一性
【发布时间】: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


    【解决方案1】:

    您需要一种更好的方法来比较日期。 像 moment 或者如果 ldInvitation.auth.expires 是时间戳,那么您可以使用 new Date.now() 进行比较。我猜那是你的问题。

    【讨论】:

    • 我现在的做法有什么问题?
    • @Boris K 我不知道 oldInvitation.auth.expires 的值和类型是时间戳是日期对象还是日期字符串?这段代码是否循环运行?为什么要使用 continue?
    • 嘿,阿米特,旧的invitation.auth.expires 是一个日期对象。代码在循环中运行,因为它正在处理用户发送的邀请数组(我不想发送整个方法 - 它很长。)
    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 2017-10-21
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多