mongodb - 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);
}
}
解决方案
这是目前的一个错误。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,
}
})
推荐阅读
- android - Android Firebase“storage.child()”不工作
- wordpress - 试图获取非对象的属性“post_title”
- python - 如何使用 ffmpeg 从图像制作视频
- javascript - 响应中的 Cookie 没有及时设置以在 React 组件中导航
- rest - Apache Camel rest 组件:尝试使用服务时已使用的地址
- html - 如何在 input="text" 表单中垂直对齐此占位符?
- bash - 在循环中将文本文件中的值分配给shell中的变量
- java - 我们可以使用 CompletableFutures 进行并行 Kafka Streams 处理吗
- python - 如何填充缺少数据但仅当差距小于某个数字时的时间序列?
- c# - 将 json 反序列化为不同程序集和命名空间的字典