我是 Go 和 React 的新手,我在這個迷你專案中使用了這兩者。Go 正在使用 Mongodb 運行后端 api。
我在 Go 中從 Mongo 獲取用戶串列,然后將其發送到 React,問題是 Mongo 給了我用戶的所有欄位(_id、密碼和用戶名),我只想要用戶名。我不明白如何過濾它并防止所有欄位從 Go 發送到 React。
Go API 的 JSON 輸出:
{
"Success": true,
"Data": [
{
"_id": "6205ac3d72c15c920a424608",
"password": {
"Subtype": 0,
"Data": "removed for security"
},
"username": "removed for security"
},
{
"_id": "6206b44afb8b044fdba76b8f",
"password": {
"Subtype": 0,
"Data": "removed for security"
},
"username": "removed for security"
}
]
}
這是我指定路線的 Go 代碼:
// Route: Get Users, for getting a list of users
func RouteGetUsers(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Set content-type to JSON
w.Header().Set("Content-Type", "application/json")
type Response struct {
Success bool `json:"Success"`
Data []bson.M `json:"Data"`
}
// Load the env file
err := godotenv.Load("variables.env")
if err != nil {
log.Fatal("Error loading .env file")
}
// Get Mongo DB environment variable
uri := os.Getenv("MONGO_URI")
if uri == "" {
log.Fatal("You must set your 'MONGO_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/#environment-variable")
}
// Connect to Mongo Database
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
// Close the database connection at the end of the function
defer func() {
if err := client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
// Select the database name and collection name
coll := client.Database("go_project1").Collection("users")
// Query the database for the user list
cursor, err := coll.Find(context.TODO(), bson.D{})
// If no documents were found, send a response and return
if err == mongo.ErrNoDocuments {
fmt.Printf("No documents were found")
return
}
// Setup a variable for the database results
var results []bson.M
// Send all database results to results variable
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
// Setup a variable with the ResponseStandard struct
response := Response{
Success: true,
Data: results,
}
// Marshal into JSON
responseJson, err := json.Marshal(response)
if err != nil {
fmt.Println(err)
}
// Send success response to user in JSON
fmt.Fprintf(w, "%s\n", responseJson)
}
uj5u.com熱心網友回復:
使用投影選項:
opts := options.Find().SetProjection(bson.D{{"username", 1}})
cursor, err := coll.Find(context.TODO(), bson.D{}, opts)
作為第二種方法:使用您想要的欄位宣告一個型別,并獲取該型別。
type Data struct {
Username string `bson:"username" json:"username"`
}
...
var data []Data
if err = cursor.All(context.TODO(), &data); err != nil { ...
...
var response = struct {
Success bool `json:"Success"`
Data []Data `json:"Data"`
}{
true,
data,
}
responseJson, err := json.Marshal(response)
...
第三種方法:過濾問題中的地圖:
for _, result := range results {
for k := range result {
if k != "username" {
delete(result, k)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/429830.html
