mongoosenext.jsmongoose-populate

Mongoose populate not working for nextjs application. Schema hasn't been registered


I've been trying to populate a list of lessonIds with the lesson documents. But I'm getting the error,

Schema hasn't been registered for model \"Lesson\".\nUse mongoose.model(name, schema)

if (req.method === "GET") {
    Course.findById(courseId)
        .populate('lessons').then(course => {
            res.json(course);
        }).catch(err => {
            res.json({ error: err.title + ' : ' + err.message });
        });
}

Now, if I import the Lesson model which registers the lessonSchema, the code does work. But I'm not using the lesson model in this file directly so I find it quite odd that I'd have to import something I won't use just to make some other feature work. Is there an appropriate way of doing this? Or somehow registering all models upon database connection?

Thank you!


Solution

  • Ended up creating a models.js inside models folder that imports all the other models and exports them to ensure Schemas get registered.