Reputation: 911
I am trying to start using Mongoose as an ODM for MongoDB with my node.js application. I have noticed that when I design a schema with an embedded document that if I don't add a value to it, it store a blank array "[]" in Mongo. Why is this? I am trying to store historical changes to records and a blank array would mean that that change deleted the value. Here is a sample schema.
schema.Client = new mongoose.Schema({
name:{type:String, required:true},
products:[{
name:{type:String, index:true},
startDate:Date,
endDate:Date
}],
subdomain:{type:String, index:{unique:true}},
})
Here is the resulting document when I save a document with just name and subdomain.
{
"name": "Smith Company",
"products": [],
"subdomain": "smith"
}
Why did it add products with a blank array by default and how can I stop it?
Upvotes: 38
Views: 24572
Reputation: 31
This worked for me. the object is not saved at all if you don't send it. this was my issue an empty object with empty sub arrays so my code was recognizing it in a forEach.
This one is referencing another schema as a subschema.
runtimeParams:{ type:[param], required:false, default:()=> undefined }, This one is a plain string array.
stages:{
type:[String],
required:false,
default:()=> undefined
},
Upvotes: 0
Reputation: 1141
By default the array has []
value. you can overwrite that :
var UserSchema = new Schema({
followers : {
type: [String],
default: undefined
}
})
Upvotes: 16
Reputation: 551
You can workaround by define the schema like below:
products: {
type: [{
name:String,
startDate:Date,
endDate:Date
}],
default: undefined
}
Upvotes: 50
Reputation: 2763
This seems to be by design, but there is a workaround here using a 'pre' handler to remove the default empty array: https://github.com/LearnBoost/mongoose/issues/1335
This only worked for me when I set the field to null
, though. If I set it to undefined
as in the sample code, the empty array seems to come back.
Upvotes: 3
Reputation: 10864
Blank array gives you convenient way to add or remove elements from your Model.
$push
$addToSet
$pull
in update would help you to manage your array elements.
If you don't have a blank array then you cannot push elements to null
But it is possible in blank array.
Upvotes: 25
Reputation: 41607
Because in your schema you are defining products to be an array of objects. You would need to try something like:
products: {
name:{type:String, index:true},
startDate:Date,
endDate:Date
},
This will store an empty object instead of an array.
Upvotes: 0