graph-gophers / graphql-go

GraphQL server with a focus on ease of use
BSD 2-Clause "Simplified" License
4.64k stars 491 forks source link

MongoDB _id field #620

Closed drksbr closed 1 year ago

drksbr commented 1 year ago

Hey guys.

It must be silly, but I'm not managing to evolve in this issue of ID fields.

Example:

# schema.graphql

type Mutation {
   createISP(isp: NewISP!): ISP!
}

type ISP {
   ID: ID!
   Name: String!
   Location: String!
   Devices: [Devices]
}

input NewISP {
   Name: String!
   Location: String!
}

// isp.resolver.go

type ISP struct {
IDField graphql.ID
NameField string
LocationField string
DevicesField *[]*Device
}

func (i *ISP) ID() graphql.ID {
    return i.IDField
}

func (i *ISP) Name() string {
    return i.NameField
}

func (i *ISP) Location() string {
    return i.LocationField
}

func (r *Resolver) GetISPs() []*ISP {

    var results []*ISP
    cursor, err := DB.Find(context.Background(), bson.M{})
    if err != nil {
        return nil
    }
    if err := cursor.All(context.Background(), &results); err != nil {
        return nil
    }
    return results
}

type NewISP struct {
    Name     string
    Location string
}

func (r *Resolver) CreateISP(args *struct{ Isp NewISP }) *ISP {

    // create new
    ispId := randomID() // Here I make a fake ID for testing because I couldn't use the id of the mongo object.

    isp := &ISP{
        IDField:       graphql.ID(ispId),
        NameField:     args.Isp.Name,
        LocationField: args.Isp.Location,
    }

    DB.InsertOne(ctx, isp)

    return isp
}

Can you help me with this issue?

pavelnikolov commented 1 year ago

What exactly is the issue?

drksbr commented 1 year ago

What exactly is the issue?

It's not really a library problem. It's my doubt about how to use the library properly.

And thank you for the wonderful work you did to come up with a super simple way to run a graphql server.

drksbr commented 1 year ago

Guys I apologize for opening the issue. I found the solution.

It would basically use the following annotation in the struct

type DeviceData struct {
    IDField     primitive.ObjectID `bson:"_id,omitempty"`
    AliasField  string             `bson:"alias"`
    IPaddrField string             `bson:"ipaddr"`
    // ServicesField *[]*Service
}

bson:"_id,omitempty"