【问题标题】:Mongoose creating empty arrays?猫鼬创建空数组?
【发布时间】:2014-01-09 21:47:03
【问题描述】:

我有以下代码:

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 属性定义为一个空数组(而不是根本不存在)。

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    根据this answer,默认情况下这样做是为了使模型能够对数组执行标准操作,这在数组为空时是可能的,但在数组为nullundefined 时不行。

    但是,可以完全删除具有空数组的属性。根据this thread 的最新更新,可以对架构进行以下修改:

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

    【讨论】:

      【解决方案2】:

      您可以将默认设置为undefined。来自 Mongoose 文档:

      var ToyBoxSchema = new Schema({
        toys: {
          type: [ToySchema],
          default: undefined
        }
      });
      

      【讨论】:

        【解决方案3】:

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

        set field as empty for mongo object using mongoose

        【讨论】:

          猜你喜欢
          • 2021-11-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-04
          • 2016-04-28
          • 2017-03-30
          • 2012-04-22
          • 2019-02-20
          相关资源
          最近更新 更多