mongoose创build空数组?

我有下面的代码:

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(); 

但是,当我从我的数据库拉这个logging它总是有items属性定义为一个空数组(而不是根本就没有)。

mongoose是故意的吗? 如果是这样的话 对我来说,强迫属性不被定义(而不是被定义为一个空数组)是不是一个好主意?

mongoose是这样做的目的,虽然我不知道为什么。 如果您将不想存储的属性设置为undefined ,则会将其从文档中排除。

使用mongoose为mongo对象设置字段为空

根据这个答案,这是默认完成的,以便使Model可以对数组执行标准操作,当数组为空时可能会执行标准操作,而当数组为空或undefined时则不可以。

但是可以用一个空数组完全删除一个属性。 根据此线程的最新更新,对模式的以下修改将会工作:

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