209 похожих чатов

ХЕЛП!!! Уже нет сил смотреть индусов с ютуба и рефы

с гитхаба...

Задача:
В nestjs через mongoose и graphql (code first) реализовать запросы product (многие к одному seller) и seller (один ко многим products), но чтобы внутри product можно было получить данные о seller и внутри seller получить массив его products[] со всеми данными.

---

Могу получить внутри product seller:

product.entity

@Field(() => Seller)
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Seller', required: true })
seller: Seller;

products.service

async getSeller(id: string): Promise<Seller> {
return this.sellerService.findOne(id);
}

---

но не могу сделать получение products из запроса seller

seller.entity

@Field(() => [Product], { nullable: true })
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Product' }] })
products?: Product[];

sellers.service

// ВОТ ЗДЕСЬ ОШИБКА (как понимаю)
async findOne(id: string): Promise<Seller> {
return this.sellerModel.findById(id).populate(['products']).exec();
}

В таком виде как сейчас получаю пустой массив products

6 ответов

17 просмотров

Делай отдельно схему для графкуэля и отдельно схему монги связи через даталоадер загружай и врезолвере указывай ResolveField вот тут у меня есть пример с даталоадером https://github.com/OpenMovieDB/openmoviedb-backend вот тут показательная модель https://github.com/OpenMovieDB/openmoviedb-backend/blob/main/src/domains/movie/movie.resolver.ts

Edward-Newsky Автор вопроса
Edward Newsky
забыл про resolver, upd сообщение https://t.me/nes...

ну у тебя кстати все просто решается. В модели seller ты обьявлешь резолвер для поля @ResolveField('products', () => [ProductModel], { nullable: true }) а в резолвере продукта @ResolveField('seller', () => SellerModel, { nullable: true })

Edward-Newsky Автор вопроса

как понимаю возникнет циркулярная зависимость, если в sellers.revolver @ResolveField для products, то придется экспортировать-импортировать products.service, а у меня уже экспортируется-импортируется sellers.service в products.revolver @ResolveField для seller - это же бэд практикс?

Edward Newsky
как понимаю возникнет циркулярная зависимость, е...

обычно в таких ситуациях указывается лимит на количество рекурсивных вызовов. Не помню есть ли у графкуэля там значение по умолчанию а импорты внутри неста не проблема разрешить обычными методами можно и кстати без импортов это сделать, подтянув через запрос монги данные

Edward-Newsky Автор вопроса
Evgenii 🇷🇺🇷🇸
обычно в таких ситуациях указывается лимит на коли...

"можно и кстати без импортов это сделать, подтянув через запрос монги данные" это не такого рода случаем запрос должен быть? вот он не работает... return this.sellerModel.findById(id).populate(['products']).exec();

Похожие вопросы

Обсуждают сегодня

@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Hello, Is iExec also part of the "inception program" or another one ? Would it be a name to qualified the nature of the relationship between iExec and Nvidia? And does Secret ...
Ñïķøłäś
8
Ready for some fun AND a chance to win TKO Tokens? Join us for exciting minigames in our Telegram group! 🕒 Don’t miss out—games start on today 25 October 2024, at 8 PM! Ge...
Milkyway | Tokocrypto
255
any reference of this implementation?
BitBuddha
29
Also, why can’t the community have a vote/ say when it comes to initiatives like buybacks. Isn’t the point of crypto decentralisation? Don’t we deserve input as long term supp...
👨🏽‍🦰
13
Hi guys, any problem with Pulsebrige? Trying to transfer from wETH to ETH. First it tells me to connect my metamask "through mobile app" not desktop. Then I did and confirmed ...
Snowflakecrypto
13
Карта сайта