2016-09-07 56 views
0

我已經爲我的集合編寫了以下貓鼬模式。然而,貓鼬模式似乎沒有對要插入文檔中的對象和項目的數據類型執行嚴格檢查。 ForExample:如果我改變mongodb插入()總是成功的

「activity_performed」:真

「activity_performed」: 「adsfsadf」

在插入數據MongoDB的不給任何錯誤。我做錯了什麼,以及如何強制mongoose和mongodb在插入數據時執行嚴格的類型檢查。

function initSchema() { 
    activitySchema = mongoose.Schema({ 
     observationNumber : Number, 
     observation_data : [{ 
      child_id : Number, 
      child_observation_data : [{ 
       activity_performed: Boolean, 
       observation_date: String, 
       teacher_id: Number 
      }] 
     }] 
    }); 
} 

function insertData() { 
    var activityModelObject = new ActivityModel(); 
    activityModelObject.observationNumber = 1593570; 
    activityModelObject.observation_data = {"child_id" : 236, child_observation_data:{"activity_performed":"adsfsadf", "observation_date": "16May2016", "teacher_id":789}}; 

    activityModelObject.save(function(err, savedObject) { 

     if(err) { 
      console.error("error in saving to mongodb", err); 
      return; 
     } 

     console.log("succesffully saveed the data: ", savedObject); 
    }); 
} 

登錄:

successfully saved the data: { observation_data: 
    [ { child_observation_data: [Object], 
     _id: 57d07545b839132412da0755, 
     child_id: 236 } ], 
    _id: 57d07545b839132412da0754, 
    observationNumber: 1593570, 
    __v: 0 } 

這應該已經失敗!但由於某種原因,mongodb報告它成功

回答

0

因爲代碼不完整。我猜你沒有用貓鼬註冊模式。所以,貓鼬甚至不知道你想強制執行任何規則。另請注意,您需要初始化new mongoose.Schema()

activitySchema = new mongoose.Schema({ 
     observationNumber : Number, 
     observation_data : [{ 
      child_id : Number, 
      child_observation_data : [{ 
       activity_performed: Boolean, 
       observation_date: String, 
       teacher_id: Number 
      }] 
     }] 
    }); 

//registering schema to Activity_Model 
var Activity = mongoose.model("Activity_Model", activitySchema); 

var activityModelObject = new Activity();