我是 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)
}
}()
}
蛊毒传说
相关分类