javascript - MongoDB 对具有相似子文档的文档进行建模

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

最佳答案

您可以使用电子邮件数组:

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

另外,

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.

您不需要迭代来更新它:

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

关于javascript - MongoDB 对具有相似子文档的文档进行建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51610094/

相关文章:

javascript - 避免在手机中加载图像

javascript - 哪个更快更好?声明一个新变量或只是分配给全局变量?

node.js - GeddyJs(NodeJs 框架)部署到 heroku cedar 堆栈崩溃

mongodb - AWS文档数据库在查找查询中不使用elemMatch运算符中的索引?

javascript - 在 map Node.js 中使用 waterfall

node.js - Mongoose findByIdAndUpdate() 查找/返回对象,但不更新

javascript - 使用 JavaScript 打开新浏览器窗口时出错

javascript - 如何使用 JavaScript 生成特定百分比更亮/更暗的 CSS 颜色

mysql - Sequelize "unique: true"使用不同的键名两次制作相同的唯一键

javascript - Node JS : SOAP to query Java Web Services