I'm having an issue with how arrays are inserted inside another array in my mongoose model. My model works fine and I'm able to update my db. First array is locationcategories[] which inside of that array, I have another categoryitems[] array. When I update the db, the categoryitems[] is stored at the beginning of the object but I needed to be stored at the end of the object.
I have this schema-model:
var Schema = mongoose.Schema;
var locationSchema = new Schema({
locationname: String,
locationdescription: String,
locationcategories: [{ categoryorder: Number, categoryname: String,
categoryitems: [] }]
});
var Location = mongoose.model('Location', locationSchema);
export default Location;
Please notice the position of categoryitems : [] at the end of my category
Here is my code to create a category object:
Location.findByIdAndUpdate(
{ _id: data.location_id },
{
$push: {
locationcategories: {
categoryorder: data.category_order,
categoryname: data.category_name,
categorydescription: data.category_description,
categoryitems: []
}
}
},
Please notice the position of categoryitems : [] at the end of my category
I get this in my mongodshell:
{
"categoryitems" : [ ],
"_id" : ObjectId("5f7d0d072b42a22490621a76"),
"categoryorder" : 4,
"categoryname" : "cat87",
"categorydescription" : "location of categoryitems"
}
Please observe where the categoryitems []. It's at the beginning of the object not at the end
That is the issue. It's suppose to insert the array at the end of the category object but instead, it is on top before the categoryorder. Is there a reason for that? I can live with it at the beginning but I'm just curious about the behavior. Am I doing something wrong? Or that is how the mongoose model works? Or is it a mongodb insert issue?
I'm very curious to figure it out. I appreciate any help.