How to make nested object return empty array if it has no value? - TypeORM Repository

121 Views Asked by At

I want the TypeORM to return empty nested if it has no value. This is my current code,

let userArea = await this.areaRepository.find({
  where: {
    userAreas: { userId:userId }, 
    stores: {
      userStores: { userId:userId }
    }
  },
  relations: ['stores']
});

If an user has a value in userAreas and userStores everything work perfectly, I will get the result like this,

[
    {
        "areaId": 1,
        "areaName": "South East",
        "stores": [
            {
                "storeId": 1,
                "storeName": "Central Station"
            },
            {
                "storeId": 2,
                "storeName": "TCE branch"
            }
        ]
    }
]

But If an user is only in userAreas but no data in userStores, I will just return the [] empty array.

My expected result is below,

[
    {
        "areaId": 1,
        "areaName": "South East",
        "stores": []
    }
]

How could I do this ? Really thanks for the help.

1

There are 1 best solutions below

0
OMartinez-NeT On

You can use OR operator:

let userArea = await this.areaRepository.find({
  where: [
    { userAreas: { userId:userId }}, 
    { stores: {
      userStores: { userId:userId }
    }
    }
  ],
  relations: ['stores']
});

When you provide an array of objects typeorm will perform OR operations between all the objects.