'Prisma creates unnecessary object hierarchy whenever many-to-many relation records are being selected

I have a many-to-many relationship between my Users and their Rewards. Using Prisma, I created an explicit relationship. Now I want to select all rewards of a given user. I wrote this function:

  async getUserRewards(userId: number) {
    const rewards = await this.prisma.userGainedRewards.findMany({
      where: {
        userId: userId,
      },
      select: {
        reward: true,
      },
    });

    return rewards;
  }

But the result is like:

[
    {
        "reward": {
            "id": 2,
            "createdAt": "2022-03-15T14:32:10.709Z",
            "updatedAt": "2022-03-15T14:32:10.709Z",
            "title": "reward 122",
            "description": "des",
            "price": 2330
        }
    },
    {
        "reward": {
            "id": 3,
            "createdAt": "2022-03-15T14:32:11.479Z",
            "updatedAt": "2022-03-15T14:32:11.479Z",
            "title": "reward 122",
            "description": "des",
            "price": 2330
        }
    }
]

As you can see I have an unncesseary unnamed object before "reward". How can I omit that?



Solution 1:[1]

This is expected behaviour from Prisma, if you would have added other fields in your select clause those would also have been added in the inner object.

To flatten out your data and removed the intermediate unnamed object you can achieve it by spreading the inner reward object.

const arr = [
    {
        "reward": {
            "id": 2,
            "createdAt": "2022-03-15T14:32:10.709Z",
            "updatedAt": "2022-03-15T14:32:10.709Z",
            "title": "reward 122",
            "description": "des",
            "price": 2330
        }
    },
    {
        "reward": {
            "id": 3,
            "createdAt": "2022-03-15T14:32:11.479Z",
            "updatedAt": "2022-03-15T14:32:11.479Z",
            "title": "reward 122",
            "description": "des",
            "price": 2330
        }
    }
]

const updatedArr = arr.map((obj)=>{
    return { ...obj.reward }
})

console.log(updatedArr)

Here is the output:

[
    {
        "id": 2,
        "createdAt": "2022-03-15T14:32:10.709Z",
        "updatedAt": "2022-03-15T14:32:10.709Z",
        "title": "reward 122",
        "description": "des",
        "price": 2330
    },
    {
        "id": 3,
        "createdAt": "2022-03-15T14:32:11.479Z",
        "updatedAt": "2022-03-15T14:32:11.479Z",
        "title": "reward 122",
        "description": "des",
        "price": 2330
    }
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nurul Sundarani