I'm populating the Customer model and transform it with helper class. But I cannot access populated field's subfields.
Order Model
const orderSchema = new Schema<IOrder>({
customerID: {
type: Schema.Types.ObjectId,
ref: "Customer",
required: true,
}
}
export const OrderModel = model<IOrder, IOrderModel>("Order", orderSchema);
Order interfaces
export interface IOrder{
_id?: Schema.Types.ObjectId;
customerID: Schema.Types.ObjectId;
}
export interface IOrderModel extends Model<IOrder> {
}
Order Helper
export class OrderHelper {
private customer: Schema.Types.ObjectId;
constructor(model: IOrder) {
this.customer = model.customerID;
}
}
Order Service
class OrderService {
private readonly orderRepository: OrderRepository;
constructor() {
this.orderRepository = new OrderRepository();
}
public async getProducts(request: Request) {
const products = await this.orderRepository.findOrders(request.body);
const data: ProductsHelper[] = [];
for (let key in products) data.push(new ProductsHelper(products[key]));
return data;
}
}
Order Repository
export class OrderRepository {
constructor() {
}
public async findOrders(body: Partial<IOrder>) {
const orders = await OrderModel.find(body)
.populate({
path: "customerID",
select: ["customerCode", "citizenship", "passportSerial"],
}).lean();
return orders;
}
}
For example, I want to access Customer's customerCode field. But it gives me TypeError that there is no field of customerCode. How can I solve this problem? Is it related with interfaces/types or something else?
CodePudding user response:
You should declare customer's type in order interface and helper. Then you will be able to access its (given interface's) fields.