cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Neo4j GraphQL how to check if node exists before connecting to it

awtsmoos-1
Node

B"H

I've seen this question and I want to do the same thing with the GraphQL driver for Neo4j. I think the answer lies somewhere in combining AND and OR operators found here, of some sort, but not sure how.

To illustrate the question, say I have this type:

 


```#graphql

type Comment  {
    id: ID @id
    timeAdded: DateTime! @timestamp(
        operations: [CREATE]
    )
    writer: User! @relationship(
        type: "WRITTEN_BY",
        direction: IN
    )
    content: String
}

type User {
   id: ID @id
   name: String
   commentsWritten: [Comment!]! @relationship(
        type: "WRITTEN_BY",
        direction: OUT
    )
}

type Mutation {
    addComment(authorID: String)
}


```

 

and this resolver to add a new comment (where "Comment" is a reference to the OGM model of the Comment type):

 


addComment: async (
        src,
        args,
        ctx
    ) => {

        var authorID = ctx.authorID //let's say this is passed
                 //from request headers / JWT token or something

        var adCom = await Comment.create({
            input: [
                {
                    content: args.content,
                    writer: {
                        connect: {
                            where: {
                                node: {
                                    users: {
                                        id: authorID
                                    }
                                }
                            }
                        }
                    }
                }
            ]
        })

        return adCom;
    }

 

So it attempts to connect to that user with that ID. but if there is no user with that ID, I don't want to create anything [not only do I not want to connect it].

I could run another query to find a User with that ID, and test if it went through, but was wondering if it's possible to do everything in one call

1 REPLY 1

You need to change your thinking here - if you don't want anything at all to be created if a user doesn't exist, you want to be updating that user as the root operation, and then performing a nested create of the comment. If the user does not exist, then this nested comment will not be created.