Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 266
Zurab-D Avatar asked Sep 08 '25 03:09

Zurab-D


2 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.

like image 165
fsevenm Avatar answered Sep 10 '25 11:09

fsevenm


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},
    email:String,
    check:[]
})

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

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": "[email protected]",
    "_id": "5915b018e292833edda8837f"
  }

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

like image 44
coder Avatar answered Sep 10 '25 12:09

coder