graphql-compose / graphql-compose-mongoose

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

Using Mongo's positional operator ($) in update mutations #394

Open LeoDupont opened 2 years ago

LeoDupont commented 2 years ago

Is it possible to use MongoDB's positional operator in a generated updateOne/updateMany resolver?

For example, I would like to make an update like this (from Mongo's doc):

db.students.updateOne(
   { _id: 1, grades: 80 },            # Finding the 80 value in the grades array
   { $set: { "grades.$" : 82 } }      # Replacing it by an 82
)

On my server, I've set the following generated update mutation:

// ...
schemaComposer.Mutation.addFields({
    studentUpdateOne: StudentTC.mongooseResolvers.updateOne(),
});
// ...

On my client, I've tried the following query and some others but I can't get the $ to not generate syntax errors:

mutation {
  studentUpdateOne(
    filter: {                     # Filtering works OK
      _id: 1,
      grades: 80
    },
    record: {                     # Updating throws syntax errors
      grades: { $: 82 }           # I also tried ` "grades.$": 82 ` and ` grades["$"]: 82 ` with no luck
    }
  ) {
    record {
      _id
      grades
    }
  }
}

I am not yet very familiar with GraphQL syntax so I may be missing an easy fix. But is it at all possible? Thanks