Golang GraphQL MongoDB努力从数据库中获取日期和ID [英] Golang GraphQL MongoDB Struggling to get date and id out of the Database

查看:90
本文介绍了Golang GraphQL MongoDB努力从数据库中获取日期和ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Golang和Graphql的新手,所以我可能搞砸了很多配置,但是我正在努力使用创建的GraphQL API从数据库返回值.每当我使用在Golang中创建的GraphQL API查询数据库时,都会引发错误,无法将UTC日期时间解码为字符串类型,并且很难获取ID.

I am new to Golang and Graphql so I probably messed a lot of the configuration up but I am struggling to get values returned from my database using the GraphQL API I created. Whenever I query my database using the GraphQL API I created in Golang It throws the error cannot decode UTC datetime into a string type and struggles to get the id out.

这是我的GrapqhQL模式:

Here is my GrapqhQL schema:

    type User {
    _id:  ID!
    username: String!
    passwordHash: String!
    email: String!
    userInfo: userStats
    profileStats: profileInfo
}



type userStats {
    firstName: String
    lastName: String
    birthday: String
    dateCreated: String!
    nativeLanguage: String
    currentlyLearning: String
    location: Location
}

type Location {
    city: String
    state: String
    zipcode: Int
    country: String
}

type profileInfo {
    level: Int
    xp: Int
    xpTillNextLevel: Int
    posts: Int
}

input NewUser {
    id: ID!
    username: String!
    passwordHash: String!
    email: String!
    userStats: String
    profileInfo: String
}

type Mutation {
    createUser(input: NewUser!): User!
}

type Query {
    users: [User!]!
    user(id: ID!): User!
}

这是提供查询时执行的代码:

Here is my code that executes when a query is provided:

func (u *UserRepo) GetUsers() ([]*model.User, error) {

    var users []*model.User

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    usersCollection := u.DB.Collection(u.KEYS["collection"].(string))

    cursor, err := usersCollection.Find(ctx, bson.M{})
    if err != nil {
        fmt.Println(err)
        return nil, err
    }

    if err = cursor.All(ctx, &users); err != nil {
        fmt.Println(err)
        return nil, err
    }
    fmt.Println(users[0])

    return users, nil
}

func (u *UserRepo) GetUserById(id string) (*model.User, error) {

    var user model.User

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    usersCollection := u.DB.Collection(u.KEYS["collection"].(string))

    userID, err := primitive.ObjectIDFromHex(id)
    if err != nil {
        fmt.Println("Invalid ObjectID")
    }

    err = usersCollection.FindOne(ctx, bson.M{"_id": userID}).Decode(&user)
    if err != nil {
        fmt.Println("error retrieving user userid : " + id)
        fmt.Printf("error: %d", err)
        //return nil, err
    }

    fmt.Println(err)

    fmt.Println(user)

    return &user, nil

}
If I uncomment the return nil,err on the bottom query for selecting one user by the id, it will just return the error of the date and no information so I am leaving it commented out for testing purposes.

我的查询和结果

query:
query getUsers {
  user(id: "5ea75c4c67f9266c89dfb659") {
    _id
    username
    email
    passwordHash
    userInfo{
      lastName
      dateCreated
      location{
        state
      }
    }
    profileStats{
      level
    }
  }
}

result: 
{
  "data": {
    "user": {
      "_id": "",
      "username": "Aerith",
      "email": "Aerith@LanguageLearning.com",
      "passwordHash": "testingpassword",
      "userInfo": {
        "lastName": "Gainsborough",
        "dateCreated": "",
        "location": null
      },
      "profileStats": null
    }
  }
}

这是我在MongoDB数据库中进行测试的示例数据集

and here is example dataset that I made for testing in my MongoDB database

db.users.findOne({_id: ObjectId("5ea75c4c67f9266c89dfb659")})
{
    "_id" : ObjectId("5ea75c4c67f9266c89dfb659"),
    "username" : "Aerith",
    "passwordHash" : "testingpassword",
    "email" : "Aerith@LanguageLearning.com",
    "userInfo" : {
        "firstName" : "Aerith",
        "lastName" : "Gainsborough",
        "birthday" : ISODate("1985-02-07T00:00:00Z"),
        "dateCreated" : ISODate("2020-04-27T22:27:24.650Z"),
        "nativeLanguage" : "English",
        "currentlyLearning" : "Japanese",
        "location" : {
            "city" : "Sector 5",
            "state" : "Midgar",
            "zipcode" : 77777,
            "country" : "FF7"
        }
    },
    "profileStats" : {
        "level" : 1,
        "xp" : 0,
        "xpTillNextLevel" : 1000,
        "comments" : 0,
        "posts" : 0
    }
}

位置和配置文件的统计信息也只是空了又为空,我不知道为什么.很抱歉,代码很长,但我正在尝试提供尽可能多的信息,以帮助找到答案.希望这会有所帮助,并且我可以就如何解决此问题获得一定的保证.谢谢您提前提供的所有帮助.

Also the location and profile stats are just coming back empty and null and I have no clue why. Sorry for the long amount of code but I am trying to provide the most information possible to assist with finding the answer. Hopefully, this helps and I can get some assurance on how to fix this issue. Thank you for all your help in advance.

edit:在对userStats类型进行一些测试之后,我可以得到firstName和lastName,但是它失败了,并且由于光标在生日时出现数据错误而导致光标崩溃.这就是为什么生日那天一切都为空的原因.因此,问题在于如何解码mongo日期,以便可以放入userStates.我很想将所有内容都作为bson并将其转换为正确的模型结构,但这似乎需要做很多额外的工作,我真的不想诉诸于此.

edit: after some testing in the userStats type I can get the firstName and lastName but it fails and the cursor crashes because of the data error when it hits birthday. This is why everything is null under birthday. So the issues is how do I decode the mongo date so I can put in the userStates. I am tempted to just pull everything as bson and convert it to correct model structs but that seems like to much extra work and I really do not want to resort to this.

推荐答案

某些BSON类型没有与Go基本类型直接映射,因此您需要使用自定义解组的类型,这些类型是您自己创建的或已经在bson/primitive上完成的包装

Some BSON types doesn't have direct mapping with Go primitive types, so you need types with custom unmarshalling, either your own made or already done on bson/primitive package

尝试以这种方式定义用户统计信息结构:

Try defining your user stats struct that way:

import "go.mongodb.org/mongo-driver/mongo/primitive"

type UserStats {
    ...
    BirthDay primitive.DateTime `bson:"birthday"`
    //OR BirthDay primitive.Timestamp `bson:"birthday"`
    ...
}

https://pkg.go.dev/go.mongodb.org/mongo-driver/bson@v1.3.3?tab = doc#hdr-Native_Go_Types

https://pkg.go.dev/go.mongodb.org/mongo-driver/bson/primitive

https://pkg.go.dev/go.mongodb.org/mongo-driver/bson/primitive?tab = doc#DateTime

https://pkg.go.dev/go.mongodb.org/mongo-driver/bson/primitive?tab = doc#Timestamp

这篇关于Golang GraphQL MongoDB努力从数据库中获取日期和ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆