我的mongoDB数据库中有这些数据。
{
"_id":"5d9ce9fd270eae22adb95d70",
...
"isdriver":true,
"driver":{
"walletmoney":0,
"license":"6eef8271-62d7-4a1c-972a-2c40a773b35a",
"vehicle":{
"image":"b6c3619b-86e6-49d0-8734-e2c48815dfc1",
"insurance":"5f8229c4-4700-4059-8b72-9344a2bc6092",
"manufacturer":"Tesla",
"model":"Model 3",
"vin":"12345678912345678",
"year":2018
},
"verified":false
...
}
}
这是我的驱动程序结构
type Driver struct {
...
Verified bool `json:"verified,omitempty"`
License string `json:"licenseimage,omitempty"`
...
Vehicle Vehicle `json:"vehicle,omitempty"`
}
这是我的学生结构
type Student struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
...
IsDriver bool `json:"isdriver,omitempty"`
Driver Driver `json:"driver,omitempty"`
}
车辆结构
type Vehicle struct {
Image string `json:"vehicleimage,omitempty"`
Insurance string `json:"insuranceimage,omitempty"`
VIN string `json:"vin,omitempty"`
Manufacturer string `json:"manufacturer,omitemptyr"` <-----(Edit) Find out this is also wrong
Model string `json:"model,omitempty"`
Year uint16 `json:"year,omitempty"`
}
我正在使用此功能从数据库中获取所有驱动程序
func GetAllDrivers() []model.Driver {
// Options
projections := bson.D{
{"driver", 1},
/* {"driver.verified", 1},
{"driver.license", 1}, */
}
// Filter for search
filter := bson.M{"isdriver": true}
// Return student collection (*mongo.Collection)
studentCollection := GetStudentCollection()
cur, err := studentCollection.Find(context.TODO(), filter, options.Find().SetProjection(projections))
// Error while finding documents
if err != nil {
fmt.Print(err)
return []model.Driver{}
}
var drivers []model.Driver
var driver model.Driver
// Get the next result from the cursor
for cur.Next(context.TODO()) {
err := cur.Decode(&driver)
if err != nil {
fmt.Print(err)
}
drivers = append(drivers, driver)
}
if err := cur.Err(); err != nil {
fmt.Print(err)
}
cur.Close(context.TODO())
return drivers
}
但是我在邮递员那里得到的答复是荒谬的
[
{
"vehicle": {
"manufacturer": ""
}
},
{
"vehicle": {
"manufacturer": ""
}
}
]
可以做的一件事情是,我得到了两个很好的对象,因为作为我的filter
建议isdriver: true
,我在数据库中总共拥有三个文档,其中两个文档有{{ 1}}。
有人可以帮助我吗?为什么我收到此回复?
答案 0 :(得分:2)
您正在学生集合中进行查找,但是您将其解码为驱动程序。 这需要更改。
var drivers []Driver
var student Student
// Get the next result from the cursor
for cur.Next(context.TODO()) {
err := cur.Decode(&student)
if err != nil {
fmt.Println(err)
}
drivers = append(drivers, student.Driver)
}
此外,您缺少Inline
的{{1}}字段的Driver
结构标记:
Student
当然,所有引用的结构都相同。工作示例代码:https://gist.github.com/mwmahlberg/c46ec3ad3ccee028f0666ff7d5d8d98b