How to make Mongoose not insert empty array or object fields into a document

Viewed 5000

Let's say we have a Mongoose schema in our Node.js project:

let coolSchema = new mongoose.Schema({
  field_1 : Number,
  field_2 : String,
  field_3 : [ String ],
});

And let's we have an according object:

var data = {
  field_1 : 123,
  field_2 : 'blah',
  field_3 : ['aa', 'bb'],
};

Now to save this data into MongoDB we can use this code:

let Model = require('mongoose').model('CoolModel', coolSchema);
(new Model(data)).save();

Ok, while it's all cool.

But if data does not contain field_3 (array field, and the same will be for an object field) Mongoose will anyway add this field into the being created document with empty value.

Can we somehow tell Mongoose not to create this field if it's not contained in the data object?

4 Answers

The accepted answer is good. But if you wouldn't want to use pre-hook, then you can add default: undefined to the array fields. For example:

var schema = new Schema({
  myArr: { type: [String], default: undefined }
});

Refer to this comment for more explanation.

It's because you're not marking the fields as required in your schema definition. Do this:

let coolSchema = new mongoose.Schema({
  field_1 : { type: Number, required: true },
  field_2 : { type: String, required: true },
  field_3 : { type: [ String ], required: true },
});
Related