Skip to content
Advertisement

Mongoose Subdocument in another Invalid Schema error

I have 2 separate files, one encapsulates the Slot Schema, and another for the Location Schema. I’m trying to have a field in the Slot Schema that references the location Schema.

   const mongoose = require('mongoose')
   const locationSchema = require('./location')

   const slotSchema = mongoose.Schema({
      time: {
        required: true,
        type: String
      },
     typeOfSlot:{
        required: true,
        type: String
     },
     academic_mem_id:{
        required: true,
        default: null,
        type: Number
     },
     course_id:{
        required: true,
        type: Number
    },
    location: [ locationSchema] // adjust
});

module.exports = mongoose.model('slots', slotSchema)

In a separate File:

const mongoose = require('mongoose')
const locationSchema =  mongoose.Schema({
    name:{
         type:String,
         required: true
    },
    capacity:{
        type: Number,
        required: true
    },
    type:{
        type:String,
        required:true
    }
});

module.exports = mongoose.model('location', locationSchema)

I get this error when I run :

 throw new TypeError('Invalid schema configuration: ' +
    ^

 TypeError: Invalid schema configuration: `model` is not a valid type within the array `location`.

I’d really appreciate it if you’d help me figure out why the code above is wrong. I want to export both the model and the Schema.

Advertisement

Answer

You are not exporting the locationSchema, but the location model. That is something entirely different and that is the reason you get the model is not a valid type within the array error.
Export only the schema and create/export the model in a separate file, e.g. locationModel.

const mongoose = require('mongoose')
const { Schema } = mongoose;

const locationSchema =  new Schema({
    name:{
         type:String,
         required: true
    },
    capacity:{
        type: Number,
        required: true
    },
    type:{
        type:String,
        required:true
    }
});

module.exports = locationSchema;

Or if you want to keep both in the same file and export both:

module.exports = {
  locationSchema,
  locationModel,
};

And import them like so:

const { locationSchema, locationModel } = require('path/to/location.js');
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement