![](/img/trans.png)
[英]Mongoose error MissingSchemaError: Schema hasn't been registered for model in typescript
[英]Mongoose getting the error: MissingSchemaError: Schema hasn't been registered for model
我收到此错误,无法弄清楚。 我已将 REF EXACLTY 命名为 MODEL:MissingSchemaError:架构尚未为 model“ParticipantStatus”注册。 这是我的模型:
参与者状态 model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const participantStatusSchema = new Schema({
_id: {
type: Number,
required: true,
},
name: {
type: String,
required: true,
},
});
module.exports = mongoose.model('ParticipantStatus', participantStatusSchema);
活动参与者 model :
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const eventParticipantSchema = new Schema(
{
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
eventId: {
type: Schema.Types.ObjectId,
ref: 'Event',
required: true,
},
teamId: {
type: Schema.Types.ObjectId,
ref: 'Team',
},
statusId: {
type: Number,
ref: 'ParticipantStatus',
required: true,
},
isActive: {
type: Boolean,
required: true,
default: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model('EventParticipant', eventParticipantSchema);
这是引发错误的代码,当我尝试获取事件参与者并填充 statusId(ParticipantStatus)时:
let participants = await EventParticipant.find(
{
eventId: req.params.eventId,
isActive: true,
},
{ _id: false }
)
.populate('userId', 'email')
.populate('statusId')
.select('userId');
我已经被困了好几个小时了。 只有.populate('statusId')部分会引发错误,rest 运行良好。 提前致谢
您要填充的字段类型应该是ObjectId
,因此将statusId
的类型从Number
更改为Schema.Types.ObjectId
,如下所示:
statusId: {
type: Schema.Types.ObjectId,
ref: 'ParticipantStatus',
required: true,
}
那么问题是你需要导入:
const ParticipantStatus = require('../models/participantStatus.model');
即使您没有在代码中直接引用它,我认为这真的很奇怪。 希望这对任何人都有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.