MongooseError:设置引用时无法读取未定义的属性“选项”

问题描述 投票:0回答:3

试图在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 } } }

像这样的Mongoose架构

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
}
mongodb mongoose mongoose-schema mongoose-populate
3个回答
1
投票

所以这是一个奇怪的,但我能够通过一些尴尬的操纵绕过它。

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

0
投票

这是你的team1定义:

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

这是你在mongo中的数据:

team1: 5835a5f653d4ce23bb33ab19

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

Mongo存储了这样的引用:

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

所以要么修复mongo中的数据,要么修复你的方案!


0
投票

您尚未正确定义架构。它应该更像是这样的:

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
},
...
});
© www.soinside.com 2019 - 2024. All rights reserved.