Mongoose Subdocument in another Invalid Schema 错误

Mongoose Subdocument in another Invalid Schema error

我有 2 个单独的文件,一个封装了 Slot Schema,另一个封装了 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)

在单独的文件中:

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)

我在 运行 :

时收到此错误
 throw new TypeError('Invalid schema configuration: ' +
    ^

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

如果您能帮我找出上面代码错误的原因,我将不胜感激。 我想同时导出模型和架构。

引用其他模型的方式是错误的。 首先,你不需要 require locationSchema,你可以在 Schema 中引用那个模块。在您的 Slot Schema 中写这个而不是您的位置字段

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

您导出的不是位置架构,而是位置模型。那是完全不同的东西,这就是你得到 model is not a valid type within the array 错误的原因。
仅将模式和 create/export 模型导出到单独的文件中,例如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;

或者如果您想将两者保存在同一个文件中并导出两者:

module.exports = {
  locationSchema,
  locationModel,
};

然后像这样导入它们:

const { locationSchema, locationModel } = require('path/to/location.js');