Mongoose populate not provided joined result

73 views Asked by At

I have two models called TodaysDeals and Products

export class TodaysDeal {

    _id: ObjectId;

    @Property({ required: true, type: Schema.Types.ObjectId, ref: "ProductsModel" })
    products: Products
}
export const TodaysDealModel = getModelForClass(TodaysDeal);

and

export class Products {

    _id: ObjectId;

    @Property({ required: true })
    productName: String;
}

export const ProductsModel = getModelForClass(Products);

I'm trying to populate the joined data, but i did'nt get the joined result.it has only contain product._id.

here is my code

 let data = await TodaysDealModel.find().populate("ProductsModel");
2

There are 2 answers

0
hasezoey On BEST ANSWER

extending on what @Vishnu said: you have 2.5 problems

  1. for populate you need to use the field name instead of the referenced model name
  2. the model name is not ProductsModel, at least not from what your code sample provided, look here to see how typegoose generates class/model names and here

and another "smaller" problem is, that you use Products as type, where Ref<Products> would be correct

your corrected code would look like:

export class TodaysDeal {
  _id: ObjectId;

  @Property({ required: true, type: Schema.Types.ObjectId, ref: "Products" })
  products: Ref<Products>;
}
export const TodaysDealModel = getModelForClass(TodaysDeal);

export class Products {
  _id: ObjectId;

  @Property({ required: true })
  productName: String;
}

export const ProductsModel = getModelForClass(Products);
let data = await TodaysDealModel.find().populate("products").exec();
0
vishnu On

You should provide the populate method with the field name provided in TodaysDealModel model.

Try

 let data = await TodaysDealModel.find().populate("products");