【发布时间】:2019-06-24 10:04:13
【问题描述】:
我有这个使用官方 mongo-go-driver (https://github.com/mongodb/mongo-go-driver) 的函数
func FindItemMongo(dataStruct interface{}, subItemKey string, collectionName string)(){
fmt.Println("inside FindDataMongo in Controller")
localDB := DB
coll := localDB.Collection(collectionName)
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
var searchData []uint8
if subItemKey==""{
fmt.Println("inside no key searchData")
searchData, _ = bson.Marshal(bson.M{"data": dataStruct})
fmt.Println("value of searchData")
fmt.Println(searchData)
fmt.Println("value of reflect type of searchData")
fmt.Println(reflect.TypeOf(searchData))
}else{
reflectItem := reflect.ValueOf(dataStruct)
subItem := reflectItem.FieldByName(subItemKey)
subItemString := subItem.Interface().(string)
searchData, _ = bson.Marshal(bson.M{"data": bson.M{strings.ToLower(subItemKey): bson.M{"$eq": subItemString}}})
fmt.Println("value of searchData")
fmt.Println(searchData)
fmt.Println("value of reflect type of searchData")
fmt.Println(reflect.TypeOf(searchData))
}
cursor, err := coll.Find(ctx, searchData)
if err != nil {
log.Fatal(err)
}
defer cursor.Close(ctx)
var returnBson []map[string]interface{}
var result bson.M
for cursor.Next(ctx) {
err := cursor.Decode(&result)
if err != nil { log.Fatal(err) }
fmt.Println("value of found parsed")
fmt.Println(result)
returnBson = append(returnBson, result)
}
}
它试图在与 if 语句相关的两个条件下查找数据库中的数据。如果未定义 subItemKey,则搜索与传入结构的完全匹配,如果定义了键,则使用 $eq 运算符在数据中搜索仅特定字段的匹配。
这适用于 subItemKey 为空的情况。像这样:
database.FindItemMongo(dataStruct, "", "users")
给
api | 1:36:55 app | value of found parsed
api | map[_id:ObjectID("8494398fsfd") data:map[email:qwer password:wer token:...]]
但是,如果我使用命令:
database.FindItemMongo(dataStruct, "Email", "users")
我什么也得不到。
我在 else 语句中定义 searchData 的方式不正确,我不确定是什么。有谁知道出了什么问题?
编辑
我应该提到
的结果 unmarshalledSearch := bson.M{"data": bson.M{strings.ToLower(subItemKey): bson.M{"$eq": subItemString}}}
fmt.Println("value of unmarshalledSearch")
fmt.Println(unmarshalledSearch)
是
api | value of unmarshalledSearch
api | map[data:map[email:map[$eq:qwer]]]
这与从空字段查询返回的数据格式相同。这是问题的症结所在——如果 searchData 的格式似乎正确,为什么光标没有返回任何结果?
【问题讨论】:
-
您的
FindItemMongo样本与上述相同。dataStruct的内容是什么? -
type Login struct{ Email stringjson:"email"` 密码字符串json:"password"令牌字符串json:"token"} ` - 你是什么意思“...和上面一样”? -
我的意思是
This works for the condition where the subItemKey is empty. Like this:和However, if I use the command:的例子 -
对不起!空的不应该有“电子邮件”子项。
标签: mongodb go mongodb-query