Search code examples
node.jspostgresqlormnode-postgresobjection.js

$relatedQuery method doesn't return modal entity


I use PostgreSQL and objection.js for ORM. When I use $relatedQuery method, I get QueryBuilder object instead of Model entities.

Here is example project and how to use $relatedQuery method.

podcastListener.js

const { Model, snakeCaseMappers } = require('objection');

class Podcast extends Model {
  static get tableName() {
    return 'podcasts_listeners';
  }

  static get columnNameMappers() {
    return snakeCaseMappers();
  }

  static get jsonSchema() {
    return {
      type: 'object',

      properties: {
        id: { type: 'integer' },
        name: { type: 'string', minLength: 1, maxLength: 100 },
      },
    };
  }

  static get relationMappings() {
    return {
      usersRel: {
        relation: Model.BelongsToOneRelation,
        modelClass: `${__dirname}/user`,
        join: {
          from: 'podcasts_listeners.user_id',
          to: 'users.id',
        },
      },

      episodesRel: {
        relation: Model.HasManyRelation,
        modelClass: `${__dirname}/episode`,
        join: {
          from: 'podcasts_listeners.id',
          to: 'episodes.podcasts_listeners_id',
        },
      },
    };
  }
}

module.exports = Podcast;

episode.js

const { Model, snakeCaseMappers } = require('objection');

class Episode extends Model {
  static get tableName() {
    return 'episodes';
  }

  static get columnNameMappers() {
    return snakeCaseMappers();
  }

  static get jsonSchema() {
    return {
      type: 'object',

      properties: {
        podcasts_listeners_id: { type: 'integer' },
        id: { type: 'integer' },
        episode_name: { type: 'string', minLength: 1, maxLength: 100 }, },
        description: { type: 'string' },
      },
    };
  }

  static get relationMappings() {
    return {
      podcastRel: {
        relation: Model.BelongsToOneRelation,
        modelClass: `${__dirname}/podcastListener`,
        join: {
          from: 'episodes.podcasts_listeners_id',
          to: 'podcasts_listeners.id',
        },
      },
    };
  }
}

module.exports = Episode;

If I run:

const podcast = await PodcastListener.query()
    .findOne('name', podcastName);

  const episode = podcast
    .$relatedQuery('episodesRel')
    .findById(6);

or:

  const episode = podcast
    .$relatedQuery('episodesRel');

episode variable is QueryBuilder instead of Episode model.

enter image description here


Solution

  • I was missing await :

    const episode = await podcast
        .$relatedQuery('episodesRel');