简体   繁体   中英

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.

That's wrong way referencing to other models. First, you don't need require locationSchema, you can refer to that module in Schema. In your Slot Schema write this instead of your location field

location: {
  type: mongoose.Schema.ObjectId,
  ref: "location"
}

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, eg 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');

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