Skip to content

Commit d0fde84

Browse files
yoadsnnodkz
authored andcommitted
docs: Document how to reuse Type of embedded object schema
Default behavior for embedded documents is to give the type a name derived from the tree-path. This shows how to force a name for that generated embedded type.
1 parent 91693fd commit d0fde84

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,72 @@ UserTC.addRelation(
157157
})
158158
);
159159
```
160+
### Reusing the same mongoose Schame in embedded object fields
161+
Suppose you have a common structure you use as embedded object in multiple Schemas.
162+
Also suppose you want the strcutre to have the same GraphQL type across all parent types.
163+
(For instance, to allow reuse of fragments for this type)
164+
Here are Schemas to demonstrate:
165+
```js
166+
import { Schema } from 'mongoose';
167+
168+
const ImageDataStructure = Schema({
169+
url: String,
170+
dimensions : {
171+
width: Number,
172+
height: Number
173+
}
174+
}, { _id: false });
175+
176+
const UserProfile = Schema({
177+
fullName: String,
178+
personalImage: ImageDataStructure
179+
});
180+
181+
const Article = Schema({
182+
title: String,
183+
heroImage: ImageDataStructure
184+
});
185+
```
186+
If you want the `ImageDataStructure` to use the same GraphQL type in both `Article` and `UserProfile` you will need to explicitly tell `graphql-compose-mongoose` that.
187+
Do the following:
188+
```js
189+
import { convertSchemaToGraphQL } from 'graphql-compose-mongoose';
190+
convertSchemaToGraphQL(ImageDataStructure, 'EmbeddedImage'); // Force this type on this mongoose schema
191+
```
192+
Before continuing to convert your models to TypeComposers:
193+
```js
194+
import mongoose from 'mongoose';
195+
import { composeWithMongoose } from 'graphql-compose-mongoose';
160196

197+
const UserProfileModel = mongoose.model('UserProfile', UserProfile);
198+
const ArticleModel = mongoose.model('Article', Article);
199+
200+
const UserProfileTC = composeWithMongoose(UserProfileModel);
201+
const ArticleTC = composeWithMongoose(ArticleModel);
202+
```
203+
Then, you can use queries like this:
204+
```graphql
205+
query {
206+
topUser {
207+
fullName
208+
personalImage {
209+
...fullImageData
210+
}
211+
}
212+
topArticle {
213+
title
214+
heroImage {
215+
...fullImageData
216+
}
217+
}
218+
}
219+
fragment fullImageData on EmbeddedImage {
220+
url
221+
dimensions {
222+
width height
223+
}
224+
}
225+
```
161226

162227
Customization options
163228
=====================

0 commit comments

Comments
 (0)