Search code examples
mongodbmongoosemongoose-schemamongoose-populate

Mongoose one-to-many relationship not being populated


I have a one-to-many relationship where a place can have multiple reviews. Here are the 2 schemas

export const PlaceSchema = new mongoose.Schema({
  name: { type: String, required: true, unique: true },
  center: { type: [Number], required: true },
  borders: { type: [], required: true },
  reviews: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Review' }]
});

export const ReviewSchema = new mongoose.Schema({
  user: { type: String, required: true },
  city: { type: mongoose.Schema.Types.ObjectId, ref: 'Place', required: true },
  creation_date: { type: Date, required: true },
  ...
});

I have reviews with correct place ID. But when I do a simple this.placeModel.find().populate('reviews').exec(), the reviews always come back as an empty array. But the IDs seem to be fine, as visible here (place on the left, review on the right)

enter image description here

It's my first side project where I play with with Mongo, so I don't really see what I'm missing.


Solution

  • Your query this.placeModel.find().populate('reviews').exec() will work in this manner:

    1. Find all place documents from the places collection.
    2. For each place document, iterate through the reviews field (of array type) and search for the document in the reviews collection with the matching id, and replace the array element with the review document.
    3. Return the list of place documents where the reviews field has been populated with the review documents.

    Hence, you need to ensure that your place documents contain the correct id of the review documents in the reviews field instead of ensuring that you have the correct place id in the review documents for the query you want to execute.