Home > Blockchain >  Populate child collection
Populate child collection

Time:12-14

This is example from mongoose docs about populate:

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
});

So, person has list of stories and when we fetch persons we can include stories by using populate('stories'). So far so good.

But in order for that to work, when creating Story, we need to add storyId to stories list in Person. I am coming from SQL background, where that does not need to be done, it would find related stories automatically based on authorId on Story.

So the question is, can it be done in same way here, without need to update stories property on Person?

CodePudding user response:

I found a solution, its called virtual property:

AuthorSchema.virtual('posts', {
  ref: 'BlogPost',
  localField: '_id',
  foreignField: 'author'
});

This way I can populate posts in query without saving postIds in Author/Person schema.

  • Related