简体   繁体   中英

MongoDB modelling a document with similar subdocuments

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));
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM