L
L
LakeForest2021-05-13 21:27:53
PHP
LakeForest, 2021-05-13 21:27:53

InvalidOperationException, until I delete items directly in the document, nothing is added. How to add item to Sokil\MongoDB array?

An error until I delete items directly in the document - nothing is added.

Fatal error: Uncaught Sokil\Mongo\Document\InvalidOperationException: The field "items" must be an array but is of type Object in /usr/src/consumer/vendor/sokil/php-mongo/src/Document.php:948
consumer_1 | Stack trace:
consumer_1 | #0 /usr/src/consumer/src/CUDReceiver.php(118): Sokil\Mongo\Document->push('items', Object(brokers\models\StructItem))

A document is created in mongodb. And until I manually delete "items: []" - it writes an error and does not add an element .. Or vice versa I will not add it. In general, I do not understand what is the reason?
{
    _id: 2,
    name: 'coffe',
    items: []
}

The code itself:
$newItem = new StructItem([
                            'id' => $data['id'],
                            'name' => $data['name'],
                            'price' => $data['price'],
                            'img_link' => $data['img_link']
                        ]);
                        $documentCategory = $collection->find()->where('_id', $data['category_id']['id'])->findOne();
                        $isExist = false;
                        try {
                            $items = $documentCategory->getItems();
                            if (count($items) > 0)
                                foreach ($items as $existItem) {
                                    if ($existItem['id'] === $data['id']) {
                                        $isExist = true;
                                        break;
                                    }
                                }
                        } catch (\Throwable $exception) {
                            echo $exception->getMessage() . " - Нет элементов \n";
                        }
                        if ($isExist) {
                            echo '[x] Exists #' . "\n";
                            break;
                        }
                        $documentCategory->push('items', $newItem);
                        $res = $documentCategory->save();

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question