猫鼬创建空数组?

Abe*_*ler 2 mongoose mongodb node.js

我有下面的代码:

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();
Run Code Online (Sandbox Code Playgroud)

但是,当我从数据库中提取此记录时,它始终具有items定义为空数组的属性(而不是根本不存在)。

猫鼬是故意这样做的吗?如果可以,为什么?尝试强制完全不定义属性(而不是将其定义为空数组)对我来说不是一个好主意吗?

Joe*_*oel 9

您可以将默认值设置为undefined. 从猫鼬文档:

var ToyBoxSchema = new Schema({
  toys: {
    type: [ToySchema],
    default: undefined
  }
});
Run Code Online (Sandbox Code Playgroud)


Emp*_*nal 8

Mongoose 确实是故意这样做的,但我不知道为什么。如果您将不想存储的属性设置为undefined,它们将从文档中排除。

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


mar*_*kru 5

根据此答案,默认情况下会完成操作,以使Model能够对数组执行标准操作,这在数组为空时是可能的,但当数组为nullor 时是不可能的undefined

但是,可以使用空数组完全删除属性。根据此线程的最新更新,可以对架构进行以下修改:

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