laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

Pushing an array to an array shows each element in the array as children, but it is inserted and fetched as expected

Open jsivil-venngage opened this issue 2 years ago • 0 comments

  • Laravel-mongodb Version: 3.9.0
  • PHP Version: 8.0.17
  • Database Driver & Version:

Description:

Steps to reproduce

  1. Push to an array
  2. Return the parent entity as json response
  3. See the items pushed are shown as each pushed.
  4. Do a GET for that entity, the item is shown as expected.

Expected behaviour

It should be consistent between the after-update and the re-fetch

Actual behaviour

The output is different from the fetch (and how it looks in the DB) from the after-update state

Example:

public function addProduct(ProductAddRequest $request, $purchaseRequestId): Response|JsonResponse
    {
        /** @var PurchaseRequest|null $purchaseRequest */
        $purchaseRequest = PurchaseRequest::find($purchaseRequestId);

        if (!$purchaseRequest) {
            return new Response("", HttpCodes::NOT_FOUND);
        }

        $product = new Product(
            $request->request->get('currency'),
            $request->request->get('unit_cost'),
            $request->request->get('product_id'),
            $request->request->get('quantity'),
        );

        $purchaseRequest->push('products', $product->toArray());   // <---------- here

        return new JsonResponse($purchaseRequest);
    }

output when adding an item:

{
    "id": "62862f04375eed096c6abc32",
    "products": [
            "id": "628667dccee1aa7afe760d24",
            "currency": "MXN",
            "unit_cost": 15999,
            "product_id": 1,
            "quantity": 1,
            "metadata": []
    ]
}

output when fetching the same item

{
    "id": "62862f04375eed096c6abc32",
    "products": [
        {
            "id": "628667dccee1aa7afe760d24",
            "currency": "MXN",
            "unit_cost": 15999,
            "product_id": 1,
            "quantity": 1,
            "metadata": []
        },
   ]
}

Note: It can be fixed by wrapping the array into a new array. Then it inserts as before, and also shows correctly in the current loaded entity.

jsivil-venngage avatar May 19 '22 16:05 jsivil-venngage