Mongoose relationship [one-to-many] best practice

100 Views Asked by At

I’m new to mongoose and I have the following question.



What’s the best practice when creating a one-to-many relationship? for example lets say I have a persons schema as follow.

const personSchema = new Schema({
  fname: String,
  lName: String,
  email: String,
  dob: Date,
  address: {
    address1: String,
    address2: String,
    city: String,
    state: String,
    zipCode: String,
  },
});

Then I have another weight schema where I have a person field referencing to the person’s object id.



const weight = new Schema({
  person: { type: Schema.Types.ObjectId, ref: 'Person' },
  date: Date,
  weight: Number,
  unit: { type: String, enum: ['kg', 'lb'] },
});

My question is: Should I also add a property field to the person’s schema with an array of the weight’s object ids?



const personSchema = new Schema({
  fname: String,
  lName: String,
  weights: [
    type: Schema.Types.ObjectId,
    ref: ‘Weight’
  ],
  email: String,
  dob: Date,
  address: {
    address1: String,
    address2: String,
    city: String,
    state: String,
    zipCode: String,
  },
});

If I don’t add the weight's array, how can I populate or bring the Person’s weight when doing a Persons.find() query?

And in case I do need to add it. When creating a new person can I also create a new weight and add it to the weigh’s array within the same Persons.Create method?


Any suggestions and guidance would be greatly appreciated. 


Thanks.


0

There are 0 best solutions below