我正在开发一个推荐功能,而且我对 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/