首页 > 解决方案 > Loopback 4/MongoDB - 外键未转换为 ObjectID

问题描述

我正在尝试使用 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);
  }
}

标签: mongodbloopbackjsloopbackobjectid

解决方案


这是目前的一个错误。hasMany / belongsTo 最终会将关系 id 保存为字符串而不是 ObjectId。您可以通过将数据库中的 id 直接更改为 ObjectId 来验证这一点,然后它会找到它。

参考:https ://github.com/strongloop/loopback-next/issues/2085

最新的每月里程碑也提到了这里,所以希望它会很快得到解决:https ://github.com/strongloop/loopback-next/issues/2313

编辑:我可以通过向模型添加 strictObjectIDCoercion 来使其工作,但是根据上面链接的问题 2085,这可能会破坏其他事情。

@model({
  settings: {
    strictObjectIDCoercion: true,
  }
})

推荐阅读