0

I used to use MySQL and now new to Mongodb. In phase of learning, I am trying to create a User Profile like LinkedIn. I am confused to choose the proper way of creating one-to-many relationship in mongodb schemas.

Context: A user can have multiple education qualification and same with experience. Here are two ways, that i tried to create the schema as:

Example 1:

var userSchema = new mongoose.Schema({
  name: {
    first: String,
    middle: String,
    last: String,
  },
  gender: { type: Number, max: 3, min: 0, default: GENDERS.Unspecified },
  age: Number,
  education: [{type: Schema.Types.ObjectId, ref:'Education'}],
  experience: [{type: Schema.Types.ObjectId, ref:'Experience'}],
  email: String
});

Example 2:

var userSchema = new mongoose.Schema({
  name: {
    first: String,
    middle: String,
    last: String,
  },
  gender: { type: Number, max: 3, min: 0, default: GENDERS.Unspecified },
  age: Number,
  education: [{type: String, detail: {
    major: String,
    degree: String,
    grade: String,
    startdate: Date,
    enddate: Date,
    remarks: String
  }}],
  experience: [{type: String, detail: {
    position: String,
    company: String,
    dateofjoin: String,
    dateofretire: String,
    location: String,
    responsibilities: [{type:String}],
    description: String,
  }}],
  email: String
});

I haven't tested the second option.

Which one is better and easier during writing querying to fetch or add data? Is there a better way to write schema for scenarios like that?

Luzan Baral
  • 3,678
  • 5
  • 37
  • 68

1 Answers1

3

For this particular example I would suggest embedding the documents vs storing as reference, and here is why.

Usually my first step in mongodb schema design is to consider how I will be querying the data?

Will I want to know the educational background of a user, or will I want to know all users who have a particular educational background? Having answers to these types of questions will determine how you want to setup your database.

If you already know your user, having the embedded educational background within that document is quick and easy to access. No separate queries are needed, and the schema still isn't overly complex and difficult to comprehend. This is how I would expect you would want to access the data.

Now, if you want to find all users with a particular educational background, there are obviously large drawbacks to the embedded document schema. In that case you would need to first look at each user, then loop through the education array to see all the various educations.

So the answer will be dependent on the expected queries you will be making to the data, but in this case (unless you are doing reporting on all users) then embedded is probably the way to go.

You may also find this discussion helpful:

MongoDB relationships: embed or reference?

Community
  • 1
  • 1
user2263572
  • 5,435
  • 5
  • 35
  • 57