How do I select specific column data to be displayed in my bookshelf model belongsTo relationship in Nodejs?

190 views Asked by At

This is a contrived example of what I would like to do:

Suppose I have a database of teams and players:

team: 
->id
->color
->rank
->division

player: 
->id
->team_id
->number
->SECRET

And the following bookshelf models:

var Base = require('./base');

const Player = Base.Model.extend(
    {
        tableName: "players",
    },
    nonsecretdata: function() {
        return this.belongsTo('Team')
    },
    {
        fields: {
            id: Base.Model.types.integer,
            team_id: Base.Model.types.integer,
            number: Base.Model.types.integer,
            SECRET: Base.Model.types.string,
        }
    }
);

module.exports = Base.model('Player', Player);

And

var Base = require('./base');

const Team = Base.Model.extend(
    {
        tableName: "teams",
    },
    {
        fields: {
            id: Base.Model.types.integer,
            color: Base.Model.types.string,
            rank: Base.Model.types.integer,
            division: Base.Model.types.string,
        }
    }
);

module.exports = Base.model('Team', Team);

My question is, how can I limit the scope of player such that SECRET is not grabbed by calls to join player and team with callback nonsecretdata?

I am new to Bookshelf so if any other information is needed, please let me know. Thank you

++++++++++ Edit: Do I need to create a separate model?

1

There are 1 answers

0
user12313 On BEST ANSWER

The only way to do this using bookshelf would be to delete the individual fields from the object after fetching the entire model.

A potentially better solution for this use case would be to define a custom Data Access Object class that uses a SQL query for the information that would like to be obtained and then use that DOA instead of using bookshelf. That way the SQL code is still abstracted away from the code that is requesting the information and the SECRET or any other potential sensitive information that is added to the table will not be included in the fetch.