Abe Miessler Abe Miessler - 4 years ago 193
Node.js Question

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download