I'm trying to store the location
of a parking Spot
in a single embedded sub-document for a cleaner object model. I want to have the coordinates
of a location
for a Spot
default to []
for every new Spot
.
When I create a Schema as follows:
var LocationSchema = new Schema({
Coordinates: {
type: [Number],
index: '2dsphere'
}
})
then embed that Schema as a sub-document in Spot
:
var SpotSchema = new Schema({
location: {
type: LocationSchema,
default: LocationSchema
}
})
var Spot = mongoose.model('Spot', SpotSchema')
and then instantiate a Spot
and try to set it's coordinates
to some value like [12, 34]
:
var spot = new Spot()
spot.location.coordinates = [12, 34]
every new Spot
I instantiate from then on has it's coordinates defaulted to that value:
var anotherSpot = new Spot()
anotherSpot.location.coordinates //returns [12, 34]
What am I doing wrong? I don't understand why modifying the property of an instance would modify the original model and by extension every new instance created from it.
EDIT
The exact same problem happens even without using a sub-document:
var SpotSchema = new Schema({
location: {
type: {
coordinates: [Number],
index: '2dsphere'
},
default: {
coordinates: []
}
}
})
var Spot = mongoose.model('Spot', SpotSchema')
var spot = new Spot()
spot.location.coordinates = [12, 34]
var anotherSpot = new Spot()
anotherSpot.location.coordinates //returns [12, 34]