简体   繁体   中英

Mongoose getting the error: MissingSchemaError: Schema hasn't been registered for model

I am getting this error and can't figure it out. I HAVE NAMED THE REF EXACLTY AS THE MODEL: MissingSchemaError: Schema hasn't been registered for model "ParticipantStatus". Here are my models:

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);

EventParticipant 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);

This is the code where the error is thrown, when i try to get event participants and populate statusId(ParticipantStatus):

 let participants = await EventParticipant.find(
  {
    eventId: req.params.eventId,
    isActive: true,
  },
  { _id: false }
)
  .populate('userId', 'email')
  .populate('statusId')
  .select('userId');

I have been stuck for hours on this. Only the .populate('statusId') part throws the error, the rest works well. Thanks in advance

type of field that you want to populate based on should be ObjectId so change the type of statusId from Number to Schema.Types.ObjectId like this:

statusId: {
    type: Schema.Types.ObjectId,
    ref: 'ParticipantStatus',
    required: true,
  }

Well the problem was that u need to import:

const ParticipantStatus = require('../models/participantStatus.model');

even if you do not REFERENCE IT DIRECTLY in your code, which is really strange in my opinion. Hope this helps anyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM