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

问题描述 投票:4回答:2

我正在尝试使用Mongo数据库建立hasMany关系。我已按照指南在loopback 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);
  }
}
mongodb loopbackjs loopback objectid
2个回答
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,
  }
})

0
投票

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

使用以下命令更新order.model:

1.进口客户模式

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

remove custId:string;

2.对于参考客户ID,只需更新代码即可

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

参考例:here

© www.soinside.com 2019 - 2024. All rights reserved.