英文:
Joining 2 structs from mongodb
问题
我有一个函数,使用.command
来检索MongoDB管理员用户。
在下面的函数中,我有DbUsers
结构体,并且我正在运行命令从两个不同的数据库中检索用户。
我的问题是,如何将这两个结果(adminUsers和externalUsers)合并后返回?它们具有相同的struct
。
type DbUsers struct {
...关于服务器的很多内容
Users []Users
}
type Users struct {
User string
...很多内容
}
func getUsers() Users {
admin := CNX.Database("admin")
external := CNX.Database("$external")
command := bson.D{primitive.E{Key: "usersInfo", Value: 1}}
var adminUsers DbUsers
var externalUsers DbUsers
err := admin.RunCommand(context.TODO(), command).Decode(&adminUsers)
if err != nil {
panic(err)
}
err2 := external.RunCommand(context.TODO(), command).Decode(&externalUsers)
if err2 != nil {
panic(err2)
}
//对于新手来说,不确定自己在做什么,但是这样做是不起作用的
return []Users{adminUsers.Users, externalUsers.Users}
}
英文:
I have a function that retrieve the mongodb admin users using .command
In the below function, I have the DbUsers
struct, and I am running the command to retrieve the users from 2 different database.
My question is, how can I concat the 2 results (adminUsers & externalUsers) and return after merged? They are of the same struct
.
type DbUsers struct {
...lots of stuff about the server
Users []Users
}
type Users struct {
User string
...lots of stuff
}
func getUsers() Users {
admin := CNX.Database("admin")
external := CNX.Database("$external")
command := bson.D{primitive.E{Key: "usersInfo", Value: 1}}
var adminUsers DbUsers
var externalUsers DbUsers
err := admin.RunCommand(context.TODO(), command).Decode(&adminUsers)
if err != nil {
panic(err)
}
err2 := external.RunCommand(context.TODO(), command).Decode(&externalUsers)
if err2 != nil {
panic(err2)
}
//New to Golang, not sure what I am doing but this doesn't work
return []Users{adminUsers.Users, externalUsers.Users}
}
答案1
得分: 1
你可以这样做:
return append(adminUsers.Users, externalUsers.Users...)
英文:
You can do
return append(adminUsers.Users, externalUsers.Users...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论