繁体   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z 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`.

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

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

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

您不是在导出 locationSchema,而是在导出位置 model。 这是完全不同的事情,这就是你得到model is not a valid type within the array错误的原因。
仅导出模式并在单独的文件中创建/导出 model,例如 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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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