17

I have the code below:

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

But when I pull this record from my database it always has the items attribute defined as an empty array (rather than not being there at all).

Is mongoose doing this on purpose? If so why? Would it be a bad idea for me to try and force the attribute to not be defined at all (rather than being defined as an empty array)?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

3 Answers3

18

You can set the default to undefined. From the Mongoose docs:

var ToyBoxSchema = new Schema({
  toys: {
    type: [ToySchema],
    default: undefined
  }
});
Joel
  • 15,654
  • 5
  • 37
  • 60
12

According to this answer it is done by default in order to enable Model to perform standard operations on arrays which is possible when the array is empty but not when it is null or undefined.

However it is possible to completely remove a property with an empty array. According to the latest updates on this thread the following modification to the schema would work:

var questionSchema = new Schema({
   items: { type: Array, default: void 0 } // <-- override the array default to be undefined
});
Community
  • 1
  • 1
margaretkru
  • 2,751
  • 18
  • 20
9

Mongoose does do this on purpose, though I'm not sure why. If you set the properties that you don't want stored as undefined, they will be excluded from the document.

set field as empty for mongo object using mongoose

Community
  • 1
  • 1
EmptyArsenal
  • 7,314
  • 4
  • 33
  • 56