How to make Mongoose not insert empty array or object fields into a document
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": "testing@gmail.com",
"_id": "5915b018e292833edda8837f"
}
so i have send only email and name but check(array) field is skipped(Not send any value).
Mongoose schema creates empty array field
When you are saving the document, mongoose look at the schema of the related collection.
It takes all fields you are giving to it and set the values up. It also create default values for the fields you did provide nothing for.
That's the behavior of mongoose.
In your case what can we do?
We gonna create two schema related to the same collection. One with the field cheese and one without. So when you gonna save a new document with the schema without cheese
, it's not gonna get created.
In practice, the collection will hold two different document type.
Here is a link about using multiple schema related to a single collection
mongoose - trying to save an array of documents, only empty array saved
The issue here is the body.modfulldata
is an array and you simply can not create mongoose schema object like this, instead iterate the array and generate mongoose schema object and then insert them. Example:
const newmods = req.body.modfulldata.map(dataObj => {
return new ModulesModel(dataObj);
});
await ModuleModel.insertMany(newmods);
Mongoose creating empty arrays?
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
Sub-document in an array saves as an empty array item if no value is provided on document creation
You can specify empty array as the default value for notes. And you don't need to return a function for the SubDocumentSchema. Try the below edited code.
const SubDocumentSchema = new mongoose.Schema({
content: {
type: String,
trim: true
},
date: {
type: Date,
default: Date.now
}
})
const DocumentSchema = new mongoose.Schema({
notes: {
type: [SubDocumentSchema],
default: []
}
});
const Document = mongooseConnection.model('DocumentSchema', DocumentSchema)
const t = new Document()
t.save()
Mongoose specify optional array of objects
In mongoose an empty array is a default value for an array type. You can override it by using default
field this way:
let optionsSchema = new mongoose.Schema(
{
answer: {
type: String,
required: true,
},
value: {
type: Number,
min: -10,
max: 10,
required: true,
},
},
{ _id: false });
const RootSchema = new Schema({
options : {
type: [optionsSchema],
default: undefined
}
})
Getting an empty array Mongoose
Specify the collection name when creating the schema, like:
const animalClassSchema = new mongoose.Schema({
name: {type: String, required: true}
}, { collection: 'animalClass' });
By default, Mongoose pluralizes your collection name. This option allows you to override that behavior. More info in the docs:
https://mongoosejs.com/docs/guide.html#collection
Related Topics
Nested Json: How to Add (Push) New Items to an Object
Regex - Get All Characters After Last Slash in Url
Cors - Response to Preflight Request Doesn't Pass Access Control Check
Enable Utf-8 Encoding for JavaScript
Regex to Match Words With Hyphens And/Or Apostrophes
How to Get List of All Timezones in JavaScript
Jquery Validation Plugin - Typeerror: $(...).Validate Is Not a Function
Get an Attribute from the Clicked Element With JavaScript
How to Export or Convert Json to Excel in Angularjs
When Click on Menu, It Opens, When Click Again It Close
How to Check If Element Has Focused Child Using JavaScript
How to Replace a String With Square Brackets Using JavaScript Replace Function
Bootstrap Modal Hide Not Working With Jquery Ajax
Change the Arrow Buttons in Slick Slider
How to Move the Mouse Pointer and Click With Selenium Webdriver JavaScript
Set Some Specific Options in Multiselect as Disabled and Selected
Can We Insert JavaScript into Any Webpage Loaded in the Browser