V
V
vincent42018-12-16 00:59:41
JavaScript
vincent4, 2018-12-16 00:59:41

GraphQL update embedded Document?

In the MongoDB documentation It is written To update a nested document You need to apply the Concatenation operator ( dot.notation ) Well, how to Make such a query (mutation) in GraphQL?
Here is the document from the database

{
    "_id" : ObjectId("5c13bab2a51af024f0c7a237"),
    "interfaceSettings" : {
        "dark" : true
        "toolbarColor" : "#fff"
    },
    "username" : "Lena",
}

And now I want to change "interfaceSettings.dark" : false
mutation {
  user{
    update(_id: "5c13bab2a51af024f0c7a237" input:{
      interfaceSettings: {dark: false}
    }
    ){
      user {
        username 
        interfaceSettings{
          dark 
          toolbarColor
        }
      }
    }
  }}

Result DB Doc
{
    "_id" : ObjectId("5c13bab2a51af024f0c7a237"),
    "interfaceSettings" : {
        "dark" : false
    },
    "username" : "Lena",
}

Backend ##############
Hier is mongoose Schema (reduced)---------------------------- -------------
const userSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  interfaceSettings: {
    dark: {
      type: Boolean,
    },
    toolbarColor: {
      type: String,
    }
   },
})

GraphQL Schema (reduced)----------------------------------------------------
type User {
    _id: ID,
    username: String
    interfaceSettings: InterfaceSettings
}

type InterfaceSettings {
    dark: Boolean,
    toolbarColor: String
}

type Mutation {
    update( _id: ID, input: InputUser): User
}
    input InputUser {
        username: String
        interfaceSettings: InputInterfaceSettings
    }
    input InputInterfaceSettings {
        dark: Boolean,
        toolbarColor: String
    }

Resolver {reduced}
GraphQL send: Input = {interfaceSettings: {dark: false}}
mutation: {
  update: async (_, { _id, input }) => {
    const user = await User.findOneAndUpdate({ _id }, { $set: input }, { new: true })
    return user
   }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question