2013-12-20 42 views
1

我有下面的代碼:Mongoose創建空數組?

var questionSchema = new schema({ 
    title: String, 
    subtitle: String, 
    required: Boolean, 
    type: String, 
    create_date: Date, 
    question_id: Number, 
    suvey_id: Number, 
    items: Array 
}); 
var question = mongoose.model("Question", questionSchema); 
var quest = getMyQuestion(); 

var record = new question({ 
    title: quest.question, 
    subtitle: quest.subtitle, 
    required: quest.answer_required, 
    type: quest.question_type, 
    create_date: quest.create_date, 
    question_id: quest.id, 
    survey_id: quest.survey_id 
}); 

record.save(); 

但是,當我拉這個記錄從我的數據庫總是有定義爲一個空數組(而不是不在那裏的話)的items屬性。

貓鼬是否故意這樣做?如果是這樣,爲什對我來說,嘗試強制屬性不被定義(而不是被定義爲空數組)是不是一個好主意?

回答

1

根據this answer它默認,以使模型上的陣列執行標準操作完成這是可能的,當數組爲空但不是當它是nullundefined

但是,可以完全刪除一個空數組的屬性。根據this thread上的最新更新,對模式的以下修改將起作用:

var questionSchema = new Schema({ 
    items: { type: Array, default: void 0 } // <-- override the array default to be undefined 
});