I'm developing a website application. In that I am storing user data and mails data. I am saving the first 15 emails in the "users" collection as a sub-document, and then storing the other mails in the "mails" collection.
I am storing first 15 mails in the user collection as I believe that most users will only need the first 15 emails at most times, thus eliminating the need to sort through the entire mails collection everytime someone opens the mails tab.
FYI: I am storing mails of every user under one mails collection, therefore, I will need to sort through the entire mails collections and find all the mails with a specific "from" or "to".
Example schema:
User Collection
var schemaUser = new mongoose.Schema({
name: "somex",
mails: [
{
from: id,
to : id,
message: String,
ref: id,
date: { type: Date, default: Date.now } // date
}
]
}
Mails Collection
var schemaMessage = new mongoose.Schema({
from: id,
to : id,
message: String,
ref: id,
date: { type: Date, default: Date.now } // date
}
});
I believe this is a very complicated process as whenever a user sends a mail, I need to first delete the last mail in that array (as the users collection will only store the latest 15 mails) and then place them in the users collection in the mail array, and then insert the deleted mail into the mails collection. A similar process is followed for deletion too.
Is there any other solution to create better schemas where we can reduce the space and processing time to fetch and update?
Thank you in advance!