Skip to content

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

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?


you can do it easily skip the array field and array of object field.. This will let you skip saving empty array in new documents.but you have to use pre hook for this .

var brandSchema = new Schema({
    name : {type:String},

brandSchema.pre('save', function (next) {
  if (this.isNew && 0 === this.check.length) {
    this.check = undefined;                                                                                                                                   

when new document is inserted in your schema you have to use this middlware.this works fine so try this. this is the response when we want to insert any document

"data": {
    "__v": 0,
    "name": "testing",
    "email": "",
    "_id": "5915b018e292833edda8837f"

so i have send only email and name but check(array) field is skipped(Not send any value).