尝试在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
}
答案 0 :(得分:1)
所以这是一个奇怪的,但我能够通过一些尴尬的操纵绕过它。
答案 1 :(得分:0)
这是您的team1
定义:
team1: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Teams'
}
这是你在mongo中的数据:
team1: 5835a5f653d4ce23bb33ab19
如您所见,team1对象类型不是ObjectId!它只是一个普通的字符串!
Mongo存储这样的引用:
team1: {
"$ref" : "Teams",
"$id" : ObjectId("5835a5f653d4ce23bb33ab19")
}
所以要么修复mongo中的数据,要么修复你的方案!
答案 2 :(得分: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
},
...
});