Отношение Loopback hasMany не возвращает данные

Я использую 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"
  }
]

person Lakshmi Narasimhan    schedule 20.06.2020    source источник
comment
К сожалению, этой информации недостаточно, чтобы точно определить проблему. Пожалуйста, предоставьте следующее: Соответствующие репозитории и полные определения модели.   -  person Rifa Achrinza    schedule 20.06.2020


Ответы (1)


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

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

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