Loopback 4/MongoDB - 外键未转换为 ObjectID

Fab*_*nCH 5 loopback mongodb objectid loopbackjs

我正在尝试使用 Mongo 数据库建立 hasMany 关系。我已按照环回 4 文档( https://loopback.io/doc/en/lb4/HasMany-relation.html )中的指南创建 hasMany 关系,并尝试设置不同的属性,但外键 custId 保存为字符串而不是 ObjectID。

我还从其他主题中找到了一些其他属性或选项,但人们正在使用 Loopback 3,但它似乎不适用于 Loopback 4。

我错过了什么或者有什么解决方法吗?

这是我的模型:

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

  @property({
    type: 'array',
    itemType: 'string',
    required: true,
  })
  product: string[];

  @property({
    type: 'number',
    required: true,
  })
  price: number;

  @property({
    type: 'string',
    id: true,
    generated: true,
  })
  custId: string;

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


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

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

  @property({
    type: 'string',
  })
  adress?: string;

  @hasMany(() => Order, {keyTo: 'custId'})
    orders?: Order[];

  constructor(data?: Partial<Customer>) {
    super(data);
  }
}
Run Code Online (Sandbox Code Playgroud)

Ift*_*ani 0

对于hasMany关系,您需要更新order模型。

更新 order.model 为:

1.导入客户模型

import {Customer} from './customer.model';
Run Code Online (Sandbox Code Playgroud)

删除 custId: 字符串;

2.作为参考客户 ID 只需更新代码即可

@belongsTo(() => Customer)
  custId: number;
Run Code Online (Sandbox Code Playgroud)

参考示例:此处