Home > database >  Mongoose Populate - Missing Schema Error, but the schema is properly registered for the model
Mongoose Populate - Missing Schema Error, but the schema is properly registered for the model

Time:12-31

Last day of 2021! After spending just over 5 hours scouring the internet I've resorted to posting for help.

Desired Behaviour:

  • the list of documents returned by the route will contain populated documents instead of only the ref ids

Attempted Resolutions:

  • added exec function after populate
  • Stackoverflow lead me down a rabbit hole of believing the issue was related to mongoose connections, and so I revamped the backend so that my model files returned schemas instead of models, and then used mongoose.createConnection instead of .connect, and made a db.js module to hold a single instance of each model (connection.mode()) that route files could then access and share. I did not reach a point where I could test .populate so I git reset back to the below code

Error

MissingSchemaError: Schema hasn't been registered for model "progressions".
Use mongoose.model(name, schema)

Note that this error is thrown when trying to populate "lesson" as well

Progress Model

const Progress = mongoose.model('Progress', new Schema({
  lesson: {
    type: Schema.Types.ObjectId,
    ref: 'lesson'
  },
  progressions: [{
    type: Schema.Types.ObjectId,
    ref: 'progression'
  }],
  progress:{
    type: Number
  },
  user:{
    type: Schema.Types.ObjectId,
    ref: 'user'
  }
},{
  timestamps: true,
}));

module.exports = Progress;

Progress Routes File

router.get('/all', async (req, res) => {
  let user = await User.find({email:req.query.user})
  let data = await Progress.find({user:user}).populate('progressions')
  return res.status(201).json({
     data,
    message: 'data populated',
    success: true
  });
});

Progression Model

const Progression = mongoose.model('Progression', new Schema({

  type:{
    type:String
  },
  toBeReviewed:{
    type: Date,
    default: Date.now
  },
},{
  timestamps: true,
}));

module.exports = Progression;

CodePudding user response:

All code in your mongoose files should have run before it is used in other files.

This error could be happening because your mongoose models aren't executed before they are used in some other file.

CodePudding user response:

did you try using "Progressions" while passing it in populate ?

  • Related