Mongoose确认错误:架构配置无效

uubf1zoe  于 2023-01-02  发布在  Go
关注(0)|答案(7)|浏览(135)

试图通过嵌入文档来对集合之间的关系进行建模,但是当在模式中进行验证并将“required”设置为True时,就会出现错误
一旦我在电影模式中注解了所需的类型对象,问题就解决了,但我需要验证

const Movie = mongoose.model(
  'Movies',
  new mongoose.Schema({
    title: {
      type: String,
      required: true,
      trim: true,
      minlength: 1,
      maxlength: 255
    },
    numberInStock: {
      type: Number,
      required: true,
      min: 0,
      max: 255
    },
    dailyRentalRate: {
      type: Number,
      required: true,
      min: 0,
      max: 255
    },
    genre: genreSchema
    required: true
  })
);

const genreSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  }
});

TypeError:无效的架构配置:True不是路径required中的有效类型

x4shl7ld

x4shl7ld1#

获取时可以使用引用填充

genre: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'genreSchema',
        required: true
    }],

有关更好的模式设计,请参阅:Model Referenced one to Many Relationship between documents

pw136qt2

pw136qt22#

删除required: true并从官方的docs中删除。注意使用的mongoose版本。我得到了同样的错误并解决了它。我的错误是将子文档作为模型而不是模式

const childSchema = new Schema({ name: 'string' });

const parentSchema = new Schema({
  // Array of subdocuments
  children: [childSchema],
  // Single nested subdocuments. Caveat: single nested subdocs only work
  // in mongoose >= 4.2.0
  child: childSchema
});
8fsztsew

8fsztsew3#

尝试在true旁边给出消息。例如--〉required:[true,“需要标题”]

e4yzc0pl

e4yzc0pl4#

请分享完整代码。
也许主要的原因是你没有习惯

const Movie = mongoose.model(
  'Movies',
  new mongoose.Schema({
    title: {
      type: String,
      required: true,
      trim: true,
      minlength: 1,
      maxlength: 255
    },
    numberInStock: {
      type: Number,
      required: true,
      min: 0,
      max: 255
    },
    dailyRentalRate: {
      type: Number,
      required: true,
      min: 0,
      max: 255
    },
    genre: {
        ref: 'SchemaName',
        required: true
    },
  })
);

你可以这样做。

s5a0g9ez

s5a0g9ez5#

将类型模型导出为exports.genreSchema = genreSchema
然后在movies.js文件中将模型导入为import { genreSchema } from './genre.model'
尝试这样做,错误将不会出现。

zujrkrfu

zujrkrfu6#

因为您忘了在这里加上","

genre: genreSchema <<<here
required: true

应为:

genre: genreSchema,
required: true
nc1teljy

nc1teljy7#

如果您遇到"required:true"问题
不要传递函数new mongoose.Schema({}),取而代之的是,你只需要创建const Schema = mongoose.Schema;,然后使用Schema({})
一定会成功的。

相关问题