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 });
- NodeJS + Express + Mongo Session存储
- 在NodeJS中stream到MongoDB
- 从nodejs插入date值到mongodb
- 如何使用mongoose和nodejs删除模型中的项目id
- 函数insertMany()无序:正确的方法来获取错误和结果?
- mongoose – 不赞成mongodb@2.2.16:请升级到2.2.19或更高?
- Node.jsasynchronouseachLimit如何在这种情况下工作?
- $ unset是空的。 您必须像这样指定一个字段:{$ unset:{<field>:…}}
- 从导出的模块返回variables并将其用于另一个文件(NodeJS)