Search code examples
node.jsmongodbmongoose

Using reference breaks mongoose model - Node.js


Concert model:

const mongoose = require('mongoose');

const concertSchema = new mongoose.Schema({
  performer: { type: String, required: true },
  genre: { type: String, required: true },
  price: { type: Number, required: true },
  day: { type: Number, required: true },
  image: { type: String, required: true },
  workshops: [{ type: mongoose.Schema.ObjectId, ref: 'Workshop' }]
});

module.exports = mongoose.model('Concert', concertSchema);

Workshop model:

const mongoose = require('mongoose');

const workshopSchema = new mongoose.Schema({
  name: { type: String, required: true },
  concertId: { type: String, required: true, }
});

module.exports = mongoose.model('Workshop', workshopSchema)

Example of concert data:

{"_id":{"$oid":"652ff8c9474981f1b2c335ca"},"id":{"$numberInt":"2"},"performer":"Rebekah Parker","genre":"R&B","price":{"$numberInt":"25"},"day":{"$numberInt":"2"},"image":"/img/uploads/2f342s4fsdg.jpg","workshops":[{"$oid":"6538f7023ebd4e3eea6c394d"},{"$oid":"6538f9803ebd4e3eea6c3958"},{"$oid":"6538f9ca3ebd4e3eea6c395a"},{"$oid":"6538fa103ebd4e3eea6c395c"}]}

When I try to use await Concert.find().populate('workshops') I get internal server error. If I don't use .populate('workshops') then everything works fine. If I change this line workshops: [{ type: mongoose.Schema.ObjectId, ref: 'Workshop' }] to just use type: String the concerts collection is returned but workshops property is omitted. I don't really have any idea what is wrong. Workshop IDs in the array are valid and have corresponding data in workshop collection


Solution

  • Your schemas look fine and the sample data for the workshops array looks typical. It is likely that your Model is not registered. Try passing the Model with the populate request:

    const concert = await Concert.find().populate({ 
       path: 'workshops',
       model: Workshop
    });