Skip to content
Advertisement

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:

JavaScript

And let’s we have an according object:

JavaScript

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

JavaScript

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?

Advertisement

Answer

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 .

JavaScript

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

JavaScript

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement