Mongoose 填充不适用于 nextjs 应用程序。架构尚未注册

1 mongoose mongoose-populate next.js

我一直在尝试使用课程文档填充 LessonIds 列表。但我收到错误,

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 });
        });
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我导入注册了 LessonSchema 的 Lesson 模型,代码就可以工作。但我没有直接使用此文件中的课程模型,因此我发现很奇怪,我必须导入一些我不会使用的东西,只是为了使其他一些功能正常工作。有适当的方法吗?或者以某种方式在数据库连接时注册所有模型?

谢谢你!

Man*_*ans 6

我遇到了这个问题并能够修复,感谢/sf/answers/3292698111/

我通过明确声明模型来修复它,如下所示:

Customer.findOne({}).populate({ path: 'created_by', model: User })
Run Code Online (Sandbox Code Playgroud)