It is more like a php issue instead of doctrine mongodb. I feel like I’m doing it wrong. So I have this Attendance data which I’m getting from db. This is how the data looks like in the db:
{
id: '1',
tags: {
item: {
active: true,
value: ['regular', 'irregular']
}
}
}
I have this method which takes two parameter, id and selectedValues. SelectedValues is an array of strings. When I call the method, it should first fetch the attendance data and then remove an element from the above object’s value array if the element doesn’t exist in selectedValues array. For example, let’s say selectedValues: ['irregular'], so then after calling the method, the object will have value array to be ['irregular'] because regular doesnt exist in selectedValus.
Another example would be if the object above has value array of ['regular'] and selectedValues array is ['irregular'], then after calling the method the values array will be [].
Right now when I call the method, both the example works fine but somehow the first example changes it to an object instead of keeping it as an array in the db. Something like { 0: 'irregular' }. Which I don’t want. I want array of strings all the time.
Here’s the code:
public function removeElementFromTagsValue(string $id, array $selectedValues)
{
$attendance = $this->repository->findOneBy([ 'id' => new ObjectId($id) ]);
$tags = $attendance->getTags();
$tagValues = $tags['item']['value'];
// remove
foreach ($tagValues as $key => $value) {
if (!in_array($value, $selectedValues)) {
unset($tagValues[$key]);
}
}
$tags['item']['value'] = $tagValues;
$attendance->setTags($tags);
$this->documentManager->persist($attendance);
$this->documentManager->flush();
return $attendance;
}