'Is there an elegant solution for auto populating other models based on Query in nest.js Graphql?

I'm sending a query from Grqphql to service and imagine I have a order model which has a relationship with owner model.

OrderResolver.ts

@Query((returns) => [Order])
  async orders() {
    return this.orderService.findAll();
  }

OrderService.ts

async findAll() {
    return (
      this.orderModel
        .find()
        .populate('owner') // => only populate if is is needed in query
        .exec()
    );
  }

Graphql query:

query{
  orders{
    id
    owner{   // only populate if this block exists
      id
      name
      email
    }
        
    paymentStatus
    status
    totalPrice
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source