mongodb insert()总是成功的

时间:2016-09-07 20:29:09

标签: node.js mongodb mongoose-schema

我为我的收藏编写了以下mongoose架构。然而,mongoose模式似乎没有对插入文档中的对象和项的数据类型执行严格检查。例如:如果我改变

" 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报告它成功

1 个答案:

答案 0 :(得分:0)

因为代码不完整。我猜你没有用mongoose注册架构。因此,mongoose甚至不知道你想要执行任何规则。另请注意,您需要初始化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();