I am trying to set up an hasMany relation using a Mongo database. I have followed the guide to create an hasMany relation in the loopback 4 documentation (https://loopback.io/doc/en/lb4/HasMany-relation.html) and tryied to set differents properties but the foreign key custId is saved as a string and not as an ObjectID.
I also found a few other properties or options from others topics but people were using Loopback 3 and it doesn't seem to work with Loopback 4.
Did I miss something or is there any workaround ?
Here are my models :
@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);
}
}
This is currently a bug. The hasMany / belongsTo will end up saving the relation id as a string instead of an ObjectId. You can verify this by changing the id in the database directly to an ObjectId and then it will find it.
Reference: https://github.com/strongloop/loopback-next/issues/2085
It is also mentioned on the latest Monthly Milestone here, so hopefully it will be resolved soon: https://github.com/strongloop/loopback-next/issues/2313
Edit: I was able to get it working by adding strictObjectIDCoercion to the model, but that can break other things according to issue 2085 linked above.
@model({
settings: {
strictObjectIDCoercion: true,
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With