2017-11-22 10 views
0

MongoDB를 통해 Invitation 객체를 적절한 컬렉션에 삽입하는 Node.js 함수가 있습니다. 스키마는 초대장의 이메일 속성이 고유해야한다고 말합니다. Async/Await을 사용하고있는 좋은 패턴에 대한 권장 사항을 사용하여 초대장이 이미 만료되었는지 여부와 그 초대가 만료되었는지 여부를 확인한 후 삭제할 수 있습니다.Mongoose with 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; 
      } 

답변

1

날짜를 비교하는 더 좋은 방법이 필요합니다. 이 moment이거나 ldInvitation.auth.expires가 타임 스탬프이면 새로운 Date.now()를 사용하여 비교할 수 있습니다. 그게 네 추측이야.

+0

내가 지금하고있는 방식으로 어떤 문제가 있습니까? –

+0

@ Boris K 글쎄, oldInvitation.auth.expires의 값과 유형이 Date 객체인지, 날짜 문자열인지는 알지 못합니다. 이 코드는 루프에서 실행됩니까? 왜 계속 사용합니까? –

+0

안녕하세요, Amit, 이전 초대장입니다 .auth.expires는 Date 개체입니다. 이 코드는 사용자가 보내는 초대장을 처리하기 때문에 루프에서 실행됩니다 (전체 메서드를 보내지 않으려 고했기 때문에 길었습니다). –