MongoDB使用相似的子文档为文档建模

时间:2018-07-31 09:31:31

标签: javascript node.js mongodb npm mongoose

我正在开发引荐功能,而我对MongoDB还是很陌生。我很难找到有关如何构建包含多个相似子文档的文档的答案。就我而言,这是4个电子邮件地址。

我不能拥有同名的属性,那么我应该如何识别它们?

我已经将它们全部保存为属性(每封电子邮件一个),但是当我以后不得不遍历它们时,对我来说似乎不切实际。

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

1 个答案:

答案 0 :(得分:1)

您可以将数组用于电子邮件:

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

也是

  

我已经将它们全部保存为属性(每封电子邮件一个),但是当我以后不得不遍历它们时,对我来说似乎不切实际。

您无需迭代即可更新它:

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