0

I'm developing a referral feature, and I'm quite new to MongoDB. I have a problem finding an answer for how to build a document that contains several similar subdocuments. In my case, it's 4 e-mails addresses.

I can't have properties with the same name, so how am I supposed to identify them?

I've had them all saved just as properties (one for each email), but it seems a bit impractical to me when I have to iterate through them later.

function submitReferrals({ accountCode, accountEmail, referrals }) {

    const email1 = referrals.email1;
    const email2 = referrals.email2;
    const email3 = referrals.email3;
    const email4 = referrals.email4;

    return getConnection().then(db => db.collection('Referrals').insertOne({
        accountCode,
        accountEmail,
        email: { name: email1, signedUp: false },
        created: new Date(),
        updated: new Date()
    }).then(el => el.value));
}
Harshal Yeole
  • 4,812
  • 1
  • 21
  • 43
user3628503
  • 43
  • 1
  • 7

1 Answers1

1

You can use the array for email:

function submitReferrals({ accountCode, accountEmail, referrals }) {

    const { email1, email2, email3, email4 } = referrals;

    return getConnection().then(db => db.collection('Referrals').insertOne({
        accountCode,
        accountEmail,
        emails: [
            { name: email1, signedUp: false },
            { name: email2, signedUp: false },
            { name: email3, signedUp: false },
            { name: email4, signedUp: false }
        ],
        created: new Date(),
        updated: new Date()
    }).then(el => el.value));
}

Also,

I've had them all saved just as properties (one for each email), but it seems a bit impractical to me when I have to iterate through them later.

You don't need to iterate for updating it:

MongoDB: How do I update a single subelement in an array, referenced by the index within the array?

Harshal Yeole
  • 4,812
  • 1
  • 21
  • 43