Home > database >  Mongoose populate one field from another id field
Mongoose populate one field from another id field

Time:08-01

I am currently having 2 fields as follows in typegoose (provides better typings for mongoose)

class User {
  @prop()
  public car: Car; // This is a single Reference

  @prop()
  public carId: Ref<Car>; // This is a single Reference
}

Now when I try to use populate method of mongoose, it fills carId field from Car collection.

But I need to fill car field using carId reference. Is there a way to do this?

When I use both Car | Ref<Car> as type, it requires lot of conversion wherever used with either <Car>cardId or carId as Car which I need to avoid as it loses the purpose of typescript.

Is there any solution to this problem?

CodePudding user response:

With public car: Car; you are basically saying that this is a sub-document, which it is not, so the proper type would be public car: Ref<Car>;. As for options, you are probably searching for Virtual Populate where you use option ref to set the class (model name) which to use for this field, option localField for the path where to look for the id on the local document and foreignField as the remote path to compare the localField against.

Example:

class User {
  @prop({ ref: () => Car, localField: 'carId', foreignField: '_id', justOne: true })
  public car?: Ref<Car>; // This is now a virtual-populate

  @prop({ ref: () => Car })
  public carId?: Ref<Car>; // This is still a single reference, which can be populated, but should also be able to be used for virtual-populate
}

Note: You could also just define carId as mongoose.Types.ObjectId if you dont want it to be populate-able.

Note: The justOne: true is required, otherwise mongoose will always return a array for virtual-populate.

  • Related