I want to design a schema for storing Contacts of Users.
Here are my existing schemas:
User Schema
_id : ObjectId("5c53653451154c6da4623a77"),
name : “something”,
email : “something”,
password : “something”,
Profile Schema
"_id" : ObjectId("5c53653451154c6da4623a88"),
user_id - ref
mobile : “something”,
company” : “something”,
designation : “something”,
website : “something”,
social: {
youtube: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
linkedin: {
type: String
},
instagram: {
type: String
}
}
I can think of two approaches to the Contact schema but both have some cons:
First approach
"_id" : ObjectId("5c53653451154c6da4623a99"),
user_id - ref,
"contacts": [
{
name : “something”,
company : “something”,
designation : “something”,
website : “something”,
social: { something },
mobile : “something”
},
{
name : “something”,
company : “something”,
designation : “something”,
website : “something”,
social: { something },
mobile : “something”
},
...
]
The problem with the above structure is that when the User updates their Profile the Contact fields can not get the updated value. But in this approach, it is easy to query and retrieve all Contacts of a particular User and send the response back.
Second approach
"_id" : ObjectId("5c53653451154c6da4623a99"),
user_id : ref,
contacts: [
profile_id,
profile_id,
profile_id,
profile_id,
profile_id,
profile_id,
...
]
In this structure Contacts have the updated User value when the User updates their Profile. But the problem here is while querying I have to fetch the profile id from the Contact schema, then query the Profile schema and return the value to the client as a response.
What happens when there are 30K-50K contacts - do I need to query the DB 50K times? Or is there a better approach?
Building on node.js, using mongoose.
Basically you have a scenario where relational database will be required. But You can also achive this in mongo .
You need to use populate of mongoose. With your second approach. Where you storing profile ids.
User.find({_id: '5c53653451154c6da4623a77'}).populate({
path:'profiles',
options: {
limit: 10,
skip: 0
}}).exec();
This query will return related profiles. If you have data like 50K. You must limit the data in one request.
NOTE: Mongodb limit for per document is 16mb. It is not possible to store that much data.
So, Just rethink your database.