簡體   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