【问题标题】:Loopback 4/MongoDB - Foreign key not converted to ObjectIDLoopback 4/MongoDB - 外键未转换为 ObjectID
【发布时间】:2019-03-15 02:24:37
【问题描述】:

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

【问题讨论】:

  • 我不知道保存为字符串的外键是否有任何相关性,但您可以在 Loopback 的 GitHub 存储库中找到一些关于关系的问题:github.com/strongloop/loopback-next/labels/Relations 很抱歉这个链接但是我不知道其中哪一个与您的问题最直接相关。即使您将外键保存为 ObjectId,我认为这种关系也行不通……

标签: mongodb loopbackjs loopback objectid


【解决方案1】:

目前这是一个错误。 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,
  }
})

【讨论】:

  • 你好@codephobia,你能解释一下解决方案吗,比如在添加设置后,你是把 id 从 string 更改为 objectid 还是保持原样?
  • @Vikranth 将设置添加到模型似乎可以解决问题。无需更改 id(从字符串到 ObjectId,反之亦然)。确保您通读了问题线程,以确保它不会影响您应用的其他部分。
【解决方案2】:

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

用 : 更新 order.model

1.导入客户模型

import {Customer} from './customer.model';

删除 custId: 字符串;

2.供参考客户ID只需更新代码

@belongsTo(() => Customer)
  custId: number;

参考示例:here

【讨论】:

  • 你成功了吗?我试过了,我添加了同样的问题,存储的 custId 有字符串而不是 ObectID。无论如何,我决定使用 UUID 而不是 ObjectID 来解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2012-01-16
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2011-12-11
相关资源
最近更新 更多