#2061·bookshelf

Related models are empty objects instead of null when not found

Author: douglasjuniorCreated Mar 4, 2020Updated Mar 24, 2022
Labelsbug
  • Related Issues: #1299, #1771

Introduction

Related models are empty objects instead of null when not found.

Issue Description

This problem still persists in 1.0.0, 1.0.1 e 1.1.0, with fetchPage and fetchAll.

For example: If in a list one record has a relation, all others records has an empty property.

json
[
    {
        "name": "Douglas",
        "address": {
            "street": "One"
        }
    },
    {
        "name": "Bruna",
        "address": { }
    },
    {
        "name": "Bel",
        "address": { }
    }
]

If no one has a relationship, then the relation property is omitted.

json
[
    {
        "name": "Bruna",
    },
    {
        "name": "Bel",
    }
]

Steps to reproduce issue

Clone this sample project https://github.com/edvaldoszy/bookshelf-empty-object-example

$ yarn install

$ yarn create-database

$ yarn fetch-non-existing-address

$ yarn fetch-existing-address

Detailed description on the sample README

Expected behaviour

The "not found" relations should be null or undefined.

json
[
    {
        "id": 1,
        "name": "Edvaldo",
        "active": 1,
        "address": null
    },
    {
        "id": 2,
        "name": "Douglas",
        "active": 1,
        "address": {
            "id": 1,
            "street": "Douglas's Street"
        }
    },
    {
        "id": 3,
        "name": "Bruna",
        "active": 1,
        "address": null
    }
]

Actual behaviour

The "not found" relations are a empty object.

json
[
    {
        "id": 1,
        "name": "Edvaldo",
        "active": 1,
        "address": {}
    },
    {
        "id": 2,
        "name": "Douglas",
        "active": 1,
        "address": {
            "id": 1,
            "street": "Douglas's Street"
        }
    },
    {
        "id": 3,
        "name": "Bruna",
        "active": 1,
        "address": {}
    }
]