Отношение Loopback hasMany не возвращает данные - PullRequest
1 голос
/ 20 июня 2020

Я использую loopback 4, а версия loopback cli - 2.2.1, и я использую коннектор MongoDB в качестве источника данных. Когда я пытаюсь фильтровать данные с помощью проводника API, я не могу получить детали заказа, отношение hasMany не работает должным образом, но в запросе заказа я могу получить подробную информацию о клиенте.

используемый запрос:

/customers?filter={"include":[{"relation":"orders"}]}

Модель клиента

import {Entity, model, property, hasMany} from '@loopback/repository';
import {Order} from './order.model';

@model()
export class Customer extends Entity {
  @property({
    type: 'string',
    id: true,
    generated: true,
  })
  id?: string;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @hasMany(() => Order)
  orders: Order[];

  constructor(data?: Partial<Customer>) {
    super(data);
  }
}

export interface CustomerRelations {
  // describe navigational properties here
}

export type CustomerWithRelations = Customer & CustomerRelations;

Модель заказа

import {Entity, model, property, belongsTo} from '@loopback/repository';
import {Customer} from './customer.model';

@model()
export class Order extends Entity {
  @property({
    type: 'string',
    id: true,
    generated: true,
  })
  id?: string;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @belongsTo(() => Customer)
  customerId: string;

  constructor(data?: Partial<Order>) {
    super(data);
  }
}

export interface OrderRelations {
  // describe navigational properties here
}

export type OrderWithRelations = Order & OrderRelations;

Репозиторий клиентов

import {Getter, inject} from '@loopback/core';
import {DefaultCrudRepository, HasManyRepositoryFactory, repository} from '@loopback/repository';
import {MongoDataSource} from '../datasources/mongo.datasource';
import {Customer, CustomerRelations} from '../models/customer.model';
import {Order} from '../models/order.model';
import {OrderRepository} from './order.repository';

export class CustomerRepository extends DefaultCrudRepository<
  Customer,
  typeof Customer.prototype.id,
  CustomerRelations
  > {

  public readonly orders: HasManyRepositoryFactory<Order, typeof Customer.prototype.id>;

  constructor(
    @inject('datasources.mongo') dataSource: MongoDataSource, @repository.getter('OrderRepository') protected orderRepositoryGetter: Getter<OrderRepository>,
  ) {
    super(Customer, dataSource);
    this.orders = this.createHasManyRepositoryFactoryFor('orders', orderRepositoryGetter,);
    this.registerInclusionResolver('orders', this.orders.inclusionResolver);
  }
}

Репозиторий заказов

import {Getter, inject} from '@loopback/core';
import {BelongsToAccessor, DefaultCrudRepository, repository} from '@loopback/repository';
import {MongoDataSource} from '../datasources/mongo.datasource';
import {Customer} from '../models/customer.model';
import {Order, OrderRelations} from '../models/order.model';
import {CustomerRepository} from './customer.repository';

export class OrderRepository extends DefaultCrudRepository<
  Order,
  typeof Order.prototype.id,
  OrderRelations
  > {

  public readonly customer: BelongsToAccessor<Customer, typeof Order.prototype.id>;

  constructor(
    @inject('datasources.mongo') dataSource: MongoDataSource, @repository.getter('CustomerRepository') protected customerRepositoryGetter: Getter<CustomerRepository>,
  ) {
    super(Order, dataSource);
    this.customer = this.createBelongsToAccessorFor('customer', customerRepositoryGetter,);
    this.registerInclusionResolver('customer', this.customer.inclusionResolver);
  }
}

Ответ

[
  {
    "id": "5eeda8af3e951001e81af9e3",
    "name": "sam"
  },
  {
    "id": "5eedbd790230752568fa5921",
    "name": "joel"
  }
]

1 Ответ

1 голос
/ 22 июня 2020

Это может быть вызвано особенностями того, как LoopBack Juggler обрабатывает идентификаторы объектов MongoDB .

Следовательно, рекомендуется сделать следующее:

  1. Добавить settings.strictObjectIDCoercion: true на всех моделях для принуждения идентификатора на уровне модели:
@model({
  settings: {
    strictObjectIDCoercion: true,
  },
})
Добавить к внешнему ключу dataType: 'ObjectId':
@belongsTo(() => Customer,
{},
{
  mongodb: {dataType: 'ObjectId'}
})
customerId: string
...