I have a collection of students that have a name and an array of email addresses. A student document looks something like this:
{
"_id": {"$oid": "56d06bb6d9f75035956fa7ba"},
"name": "John Doe",
"emails": [
{
"label": "private",
"value": "[email protected]"
},
{
"label": "work",
"value": "[email protected]"
}
]
}
The label in the email subdocument is set to be unique per document, so there can't be two entries with the same label.
My problems is, that when updating a student document, I want to achieve the following:
- adding an email with a new label should simply add a new subdocument with the given label and value to the array
- if adding an email with a label that already exists, the value of the existing should be set to the data of the update
For example when updating with the following data:
{
"_id": {"$oid": "56d06bb6d9f75035956fa7ba"},
"emails": [
{
"label": "private",
"value": "[email protected]"
},
{
"label": "school",
"value": "[email protected]"
}
]
}
I would like the result of the emails array to be:
"emails": [
{
"label": "private",
"value": "[email protected]"
},
{
"label": "work",
"value": "[email protected]"
},
{
"label": "school",
"value": "[email protected]"
}
]
How can I achieve this in MongoDB (optionally using mongoose)? Is this at all possible or do I have to check the array myself in the application code?