从MongoDB在Go API中过滤显示的信息。

huangapple go评论110阅读模式
英文:

Filtering what information is displayed from MongoDB in Go api

问题

我是Go和React的新手,我正在使用它们进行这个小项目。Go正在运行一个使用Mongodb的后端API。

我在Go中从Mongo中获取用户列表,然后将其发送到React,问题是Mongo给我返回了用户的所有字段(_id、password和username),我只想要username字段。我不明白如何过滤这些字段并阻止所有字段从Go发送到React。

Go API的JSON输出:

  1. {
  2. "Success": true,
  3. "Data": [
  4. {
  5. "_id": "6205ac3d72c15c920a424608",
  6. "password": {
  7. "Subtype": 0,
  8. "Data": "removed for security"
  9. },
  10. "username": "removed for security"
  11. },
  12. {
  13. "_id": "6206b44afb8b044fdba76b8f",
  14. "password": {
  15. "Subtype": 0,
  16. "Data": "removed for security"
  17. },
  18. "username": "removed for security"
  19. }
  20. ]
  21. }

这是我指定路由的Go代码:

  1. // 路由:获取用户列表
  2. func RouteGetUsers(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
  3. // 设置内容类型为JSON
  4. w.Header().Set("Content-Type", "application/json")
  5. type Response struct {
  6. Success bool `json:"Success"`
  7. Data []bson.M `json:"Data"`
  8. }
  9. // 加载环境变量文件
  10. err := godotenv.Load("variables.env")
  11. if err != nil {
  12. log.Fatal("加载.env文件时出错")
  13. }
  14. // 获取Mongo DB环境变量
  15. uri := os.Getenv("MONGO_URI")
  16. if uri == "" {
  17. log.Fatal("您必须设置您的'MONGO_URI'环境变量。请参阅\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/#environment-variable")
  18. }
  19. // 连接到Mongo数据库
  20. client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
  21. if err != nil {
  22. panic(err)
  23. }
  24. // 在函数结束时关闭数据库连接
  25. defer func() {
  26. if err := client.Disconnect(context.TODO()); err != nil {
  27. panic(err)
  28. }
  29. }()
  30. // 选择数据库名称和集合名称
  31. coll := client.Database("go_project1").Collection("users")
  32. // 查询数据库获取用户列表
  33. cursor, err := coll.Find(context.TODO(), bson.D{})
  34. // 如果没有找到文档,则发送响应并返回
  35. if err == mongo.ErrNoDocuments {
  36. fmt.Printf("未找到文档")
  37. return
  38. }
  39. // 设置一个变量用于存储数据库结果
  40. var results []bson.M
  41. // 将所有数据库结果发送到results变量
  42. if err = cursor.All(context.TODO(), &results); err != nil {
  43. panic(err)
  44. }
  45. // 使用Response结构设置一个变量
  46. response := Response{
  47. Success: true,
  48. Data: results,
  49. }
  50. // 转换为JSON
  51. responseJson, err := json.Marshal(response)
  52. if err != nil {
  53. fmt.Println(err)
  54. }
  55. // 以JSON格式向用户发送成功响应
  56. fmt.Fprintf(w, "%s\n", responseJson)
  57. }
英文:

I am new to Go and React, both of which I am using for this mini project. Go is running a backend api using Mongodb.

I am fetching the user list from Mongo in Go, and then sending that to React, problem is Mongo is giving me all of the fields for the user (_id, password, and username), I only want username. I am not understanding how I can filter this and prevent all fields from being sent from Go to React.

JSON Output from Go API:

  1. {
  2. "Success": true,
  3. "Data": [
  4. {
  5. "_id": "6205ac3d72c15c920a424608",
  6. "password": {
  7. "Subtype": 0,
  8. "Data": "removed for security"
  9. },
  10. "username": "removed for security"
  11. },
  12. {
  13. "_id": "6206b44afb8b044fdba76b8f",
  14. "password": {
  15. "Subtype": 0,
  16. "Data": "removed for security"
  17. },
  18. "username": "removed for security"
  19. }
  20. ]
  21. }

Here is my Go code for the specified route:

  1. // Route: Get Users, for getting a list of users
  2. func RouteGetUsers(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
  3. // Set content-type to JSON
  4. w.Header().Set("Content-Type", "application/json")
  5. type Response struct {
  6. Success bool `json:"Success"`
  7. Data []bson.M `json:"Data"`
  8. }
  9. // Load the env file
  10. err := godotenv.Load("variables.env")
  11. if err != nil {
  12. log.Fatal("Error loading .env file")
  13. }
  14. // Get Mongo DB environment variable
  15. uri := os.Getenv("MONGO_URI")
  16. if uri == "" {
  17. log.Fatal("You must set your 'MONGO_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/#environment-variable")
  18. }
  19. // Connect to Mongo Database
  20. client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
  21. if err != nil {
  22. panic(err)
  23. }
  24. // Close the database connection at the end of the function
  25. defer func() {
  26. if err := client.Disconnect(context.TODO()); err != nil {
  27. panic(err)
  28. }
  29. }()
  30. // Select the database name and collection name
  31. coll := client.Database("go_project1").Collection("users")
  32. // Query the database for the user list
  33. cursor, err := coll.Find(context.TODO(), bson.D{})
  34. // If no documents were found, send a response and return
  35. if err == mongo.ErrNoDocuments {
  36. fmt.Printf("No documents were found")
  37. return
  38. }
  39. // Setup a variable for the database results
  40. var results []bson.M
  41. // Send all database results to results variable
  42. if err = cursor.All(context.TODO(), &results); err != nil {
  43. panic(err)
  44. }
  45. // Setup a variable with the ResponseStandard struct
  46. response := Response{
  47. Success: true,
  48. Data: results,
  49. }
  50. // Marshal into JSON
  51. responseJson, err := json.Marshal(response)
  52. if err != nil {
  53. fmt.Println(err)
  54. }
  55. // Send success response to user in JSON
  56. fmt.Fprintf(w, "%s\n", responseJson)
  57. }

答案1

得分: 1

使用投影选项:

  1. opts := options.Find().SetProjection(bson.D{{"username", 1}})
  2. cursor, err := coll.Find(context.TODO(), bson.D{}, opts)

作为第二种方法:声明一个包含你想要的字段的类型,并将其提取到该类型中。

  1. type Data struct {
  2. Username string `bson:"username" json:"username"`
  3. }
  4. ...
  5. var data []Data
  6. if err = cursor.All(context.TODO(), &data); err != nil { ...
  7. ...
  8. var response = struct {
  9. Success bool `json:"Success"`
  10. Data []Data `json:"Data"`
  11. }{
  12. true,
  13. data,
  14. }
  15. responseJson, err := json.Marshal(response)
  16. ...

第三种方法:过滤问题中的映射:

  1. for _, result := range results {
  2. for k := range result {
  3. if k != "username" {
  4. delete(result, k)
  5. }
  6. }
  7. }
英文:

Use the projection option:

  1. opts := options.Find().SetProjection(bson.D{{"username", 1}})
  2. cursor, err := coll.Find(context.TODO(), bson.D{}, opts)

As second approach: Declare a type with the fields you want, and fetch to that type.

  1. type Data struct {
  2. Username string `bson:"username" json:"username"`
  3. }
  4. ...
  5. var data []Data
  6. if err = cursor.All(context.TODO(), &data); err != nil { ...
  7. ...
  8. var response = struct {
  9. Success bool `json:"Success"`
  10. Data []Data `json:"Data"`
  11. }{
  12. true,
  13. data,
  14. }
  15. responseJson, err := json.Marshal(response)
  16. ...

A third approach: Filter the maps in the question:

  1. for _, result := range results {
  2. for k := range result {
  3. if k != "username" {
  4. delete(result, k)
  5. }
  6. }
  7. }

huangapple
  • 本文由 发表于 2022年2月19日 02:55:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/71178546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定