question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

update mutation on nested document fails

See original GitHub issue

Hi, I’m trying to update a nested document including an EmbeddedDocumentListField / EmbeddedDocument with graphene-mongo. Creating a new user via create mutation works perfectly fine, but when I try to update a nested document, it fails with the error Invalid embedded document instance provided to an EmbeddedDocumentField: ['label']

Here is my code: models.py:

from mongoengine import Document, EmbeddedDocumentListField, EmbeddedDocument
from mongoengine.fields import StringField


class UserLabel(EmbeddedDocument):
    code = StringField()
    value = StringField()


class User(Document):
    meta = {'collection': 'user'}
    first_name = StringField(required=True)
    last_name = StringField(required=True)
    label = EmbeddedDocumentListField(UserLabel)

app.py:

from flask import Flask
from flask_graphql import GraphQLView
import graphene
from graphene_mongo import MongoengineObjectType
from mongoengine import connect
from models import User as UserModel, UserLabel as UserLabelModel

app = Flask(__name__)

class UserLabel(MongoengineObjectType):
    class Meta:
        model = UserLabelModel


class User(MongoengineObjectType):
    class Meta:
        model = UserModel


class UserLabelInput(graphene.InputObjectType):
    code = graphene.String()
    value = graphene.String()


class UserInput(graphene.InputObjectType):
    id = graphene.String()
    first_name = graphene.String()
    last_name = graphene.String()
    label = graphene.List(UserLabelInput, required=False)


class Query(graphene.ObjectType):
    users = graphene.List(User)

    def resolve_users(self, info):
        return list(UserModel.objects.all())


class createUser(graphene.Mutation):
    user = graphene.Field(User)

    class Arguments:
        user_data = UserInput()

    def mutate(root, info, user_data):
        user = UserModel(
            first_name=user_data.first_name,
            last_name=user_data.last_name,
            label=user_data.label
        )
        user.save()
        return createUser(user=user)


class updateUser(graphene.Mutation):
    user = graphene.Field(User)

    class Arguments:
        user_data = UserInput()

    def mutate(self, info, user_data):
        user = UserModel.objects.get(id=user_data.id)

        if user_data.first_name:
            user.first_name = user_data.first_name
        if user_data.last_name:
            user.last_name = user_data.last_name
        if user_data.label:
            user.label = user_data.label

        user.save()
        return updateUser(user=user)


class Mutation(graphene.ObjectType):
    create_user = createUser.Field()
    update_user = updateUser.Field()


schema = graphene.Schema(query=Query, mutation=Mutation)
app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True))

if __name__ == '__main__':
    app.run(debug=True, port=1234)

Trying to run this update mutation via graphiql :

mutation {
  updateUser(userData: {
    id: "5d6f8bbbe3ec841d93229322",
    firstName: "Peter",
    lastName: "Simpson",
    label: [
      {
        code:"DE",
        value: "Peter Simpson"
      }
    ]
  }) {
    user {
      id
      firstName
      lastName
      label {
        code
        value
      }
    }
  }
}

I get the error:

{
  "errors": [
    {
      "message": "ValidationError (User:5d6f8bbbe3ec841d93229322) (Invalid embedded document instance provided to an EmbeddedDocumentField: ['label'])",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "updateUser"
      ]
    }
  ],
  "data": {
    "updateUser": null
  }
} 

Updating without the nested field works perfectly fine. How can I resolve this ?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
fantasylwcommented, Dec 16, 2020

Hi, I solved this problem.

Solution:

Create the class in the schema.py file:

from graphene_mongo import MongoengineConnectionField, MongoengineObjectType from graphene.relay import Node from models import StepsNode

class Steps(MongoengineObjectType): class Meta: model = StepsNode interfaces = (Node,)

models.py

class StepsNode(EmbeddedDocument): name = StringField()

0reactions
abawchencommented, Jan 9, 2021

close this one, and feel free to reopen it if needed.

Read more comments on GitHub >

github_iconTop Results From Across the Web

UpdateInputs replace entire entries when mutating nested ...
When I tried to create my own, I experienced some weird issues: GraphQl query with custom resolver for handling nested objects fails at...
Read more >
How to update nested item in GraphQL wp-graphql
I am trying to edit one of Custom Post Types Ranking so that the upvotes field inside Ranking > ranking > rankingsPost >...
Read more >
Beware of GraphQL Nested Mutations! - freeCodeCamp
A reader pointed me to an issue on the GraphQL GitHub site where it was stated that the execution order of nested mutations...
Read more >
Multiple mutations in a request | Hasura GraphQL Docs
If multiple mutations are part of the same request, they are executed sequentially in a single transaction. If any of the mutations fail,...
Read more >
Supporting opt-in nested mutations in GraphQL
Discover the benefits of offering nested mutations as an opt-in feature ... Post.update is applied on the object created by mutation Root.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found