我正面臨着這個奇怪的問題,它給了我一個特定模式的ValidationError。我不太確定這次事故的原因,因爲對象的類型對我來說似乎很完美。驗證錯誤Mongodb
// works fine but the Data in ObservationsObject is LOST
var ObservationsObject = Observations.ObservationsModel(timeTable.learningCenter.observations);
var LearningCenterObject = LearningCenter.LearningCenterModel(timeTable.learningCenter);
LearningCenterObject.observations = ObservationsObject;
// GIVES VALID ERROR UPON LEARNINGCENTER.SAVE()
var LearningCenterObject = LearningCenter.LearningCenterModel(timeTable.learningCenter);
for (var i = 0; i < timeTable.learningCenter.observations.length; i++) {
var ObservationsObject = Observations.ObservationsModel(timeTable.learningCenter.observations[i]);
LearningCenterObject.observations.push(ObservationsObject);
}
可以節省代碼:
LearningCenterObject.save(function (err, learningCenterSavedObject) {
if (err) {
console.error("TimeTableController->LearningCenterObject->save()", err);
return;
}
console.log("TimeTableController->LearningCenterObject->save() SUCCESS");
ObservationsObject.save(function (err, observationSavedObject) {
if (err) {
console.error("TimeTableController->LearningCenterObject->Observations->save()", err);
return;
}
console.log("TimeTableController->LearningCenterObject->Observations->save() SUCCESS");
});
});
架構:
learningCenterSchema = new mongoose.Schema({
name : String,
observations: [{type: Schema.Types.ObjectId, ref: "observations_model"}]
});
observationsSchema = new mongoose.Schema({
obsNum : String,
data: {ageGroup : String, category: String, description: String, tips: String}
});
錯誤:
TimeTableController->LearningCenterObject->save() { [ValidationError: learning_center_model validation failed]
message: 'learning_center_model validation failed',
name: 'ValidationError',
errors:
{ observations:
{ [CastError: Cast to Array failed for value "[object Object]" at path "observations"]
message: 'Cast to Array failed for value "[object Object]" at path "observations"',
name: 'CastError',
kind: 'Array',
value: [Object],
path: 'observations',
reason: [Object] } } }
樣品JSON:
"learningCenter": {
"name": "asdf",
"observations": [
{
"obsNum": "1.1111",
"data": {
"ageGroup": "sadf",
"category": "df",
"description": "adf",
"tips": "asdf"
}
}
]
}