【问题标题】:Mongoose Subdocument in another Invalid Schema error另一个 Invalid Schema 错误中的 Mongoose 子文档
【发布时间】:2021-03-27 23:51:45
【问题描述】:

我有 2 个单独的文件,一个封装 Slot Schema,另一个用于 Location Schema。我试图在 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`.

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

【问题讨论】:

    标签: javascript node.js mongodb mongodb-query mongoose-schema


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您不是在导出 locationSchema,而是在导出位置模型。这是完全不同的事情,这就是您收到 model is not a valid type within the array 错误的原因。
      仅导出模式并在单独的文件中创建/导出模型,例如位置模型。

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

      【讨论】:

      • 这会显示错误“架构数组路径的值无效。架构数组路径'位置'的值无效,值未定义”。如何同时导出两者? locationSchema 和模型?
      • @Hoda 为您扩展了答案
      猜你喜欢
      • 2016-12-14
      • 1970-01-01
      • 2020-09-26
      • 2021-07-31
      • 2015-10-31
      • 2012-12-26
      • 2011-09-12
      • 2020-03-02
      相关资源
      最近更新 更多