Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose creating empty arrays?

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)?

like image 357
Abe Miessler Avatar asked Dec 20 '13 23:12

Abe Miessler


1 Answers

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

var ToyBoxSchema = new Schema({
  toys: {
    type: [ToySchema],
    default: undefined
  }
});
like image 119
Joel Avatar answered Oct 08 '22 13:10

Joel