首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang GraphQL MongoDB正在努力从数据库中获取日期和id

Golang GraphQL MongoDB正在努力从数据库中获取日期和id
EN

Stack Overflow用户
提问于 2020-04-30 04:46:48
回答 1查看 934关注 0票数 0

我刚接触Golang和Graphql,所以我可能把很多配置搞得一团糟,但是我很难使用我创建的GraphQL应用程序接口从我的数据库中获取返回值。每当我使用我在Golang中创建的UTC查询我的数据库时,它都抛出错误,无法将GraphQL日期时间解码为字符串类型,并且很难获得id。

下面是我的GrapqhQL模式:

代码语言:javascript
复制
    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!
}

下面是我的代码,它在提供查询时执行:

代码语言:javascript
复制
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.

我的查询和结果

代码语言:javascript
复制
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数据库中进行测试而创建的示例数据集

代码语言:javascript
复制
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
    }
}

此外,位置和配置文件统计数据返回时都是空的,我不知道为什么。很抱歉代码太长了,但我正在努力提供尽可能多的信息来帮助找到答案。希望这会有所帮助,我可以在如何解决这个问题上得到一些保证。提前感谢您的帮助。

编辑:在对userStats类型进行一些测试之后,我可以获得firstName和lastName,但是它失败了,并且光标在遇到生日时由于数据错误而崩溃。这就是为什么生日下所有的东西都是空的。所以问题是我如何解码mongo date,以便我可以放入userStates。我很想把所有东西都转换成正确的模型结构,但这似乎需要很多额外的工作,我真的不想求助于此。

EN

回答 1

Stack Overflow用户

发布于 2020-05-07 16:32:36

一些BSON类型没有与Go原语类型的直接映射,因此您需要具有自定义解组的类型,无论是您自己创建的类型,还是已经在bson/primitive包中完成的类型。

试着这样定义你的用户统计结构:

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61511365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档