graphql-compose / graphql-compose-mongoose

Mongoose model converter to GraphQL types with resolvers for graphql-compose https://github.com/nodkz/graphql-compose
MIT License
708 stars 94 forks source link

Add relation to nested ObjectID array #350

Open pixel-mattp opened 3 years ago

pixel-mattp commented 3 years ago

I have a Schema as follows:

export const ProductSchema = new Schema(
    {
        colours: {
            type: [
                {
                    colour: {
                        type: mongoose.Schema.Types.ObjectId,
                        ref: 'Colour',
                    },
                    price: { type: String },
                },
            ],
            required: false,
        }
    },
    {
        collection: 'products',
    }
);

I am trying to use the addRelation function to populate the colour object inside each array item, however because it's within a nested array (not an object) I'm struggling to make it work.

Am I missing something?

Thanks!

henrikwikstrom commented 3 years ago

You have to add a releation to your ObjectTypeComposer object, like this

TC.getFieldOTC("colours").addRelation("colour", { resolver: () => ColorTC.mongooseResolvers.findByIds(), prepareArgs: { _ids: (source) => source.colours.map((o) => o._id) || null, }, projection: { colour: true }, });