MongooseError: Cannot read property 'options' of undefined when setting reference

MongooseError: Cannot read property 'options' of undefined when setting reference

尝试在 Mongoose 中设置一个简单的引用字段给我带来了巨大的问题。 我收到以下错误。据我所知,没有实际的验证错误。

'contents.0.modules.0.matches.0.':
      { MongooseError: Cannot read property 'options' of undefined
          at ValidatorError (C:\Users\Simon\Documents\Projects\eventvods\node_modules\mongoose\lib\error\validator.js:24:11)
          at _init (C:\Users\Simon\Documents\Projects\eventvods\node_modules\mongoose\lib\document.js:372:37)
          ...
          at init (C:\Users\Simon\Documents\Projects\eventvods\node_modules\mongoose\lib\document.js:348:7)
          at model.Document.init (C:\Users\Simon\Documents\Projects\eventvods\node_modules\mongoose\lib\document.js:313:3)
        message: 'Cannot read property \'options\' of undefined',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'cast',
        path: undefined,
        value: undefined } } }

像这样的猫鼬模式

var matchSchema = new Schema({

    team1: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Teams'
    },
    team2: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Teams'
    },
    team1_2: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Teams'
    },
    team2_2: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Teams'
    },
    ...
});
var moduleSchema = new Schema({
    matches: [matchSchema],
    ...
});
var sectionSchema = new Schema({
    modules: [moduleSchema],
    ...
});

保存失败的示例对象:

{ 
  team1: 5835a5f653d4ce23bb33ab19,
  team2: 5835a70353d4ce23bb33ab21
}

这是您的 team1 定义:

team1: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Teams'
}

这是您在 mongo 中的数据:

team1: 5835a5f653d4ce23bb33ab19

如您所见,team1对象类型不是ObjectId!这只是一个普通的字符串!

Mongo 存储这样的引用:

team1: {
    "$ref" : "Teams",
    "$id" : ObjectId("5835a5f653d4ce23bb33ab19")
}

因此,要么在 mongo 中修复您的数据,要么修复您的方案!

所以这是一个奇怪的问题,但我能够通过一些笨拙的操作绕过它。

  1. 正在创建一个相同类型的新架构字段,并将其设置为 值。
  2. 浏览我所有的文档,并设置 原始字段到该字段的值。

您没有正确定义架构。应该更像这样:

var matchSchema = new Schema({

team1: {
    type: mongoose.Schema.Types.ObjectId,
    ref: String
},
team2: {
    type: mongoose.Schema.Types.ObjectId,
    ref: String
},
team1_2: {
    type: mongoose.Schema.Types.ObjectId,
    ref: String
},
team2_2: {
    type: mongoose.Schema.Types.ObjectId,
    ref: String
},
...
});