英文:
How to build mgo queries?
问题
我正在使用revel和mgo做一个小项目(练习),但是在构建查询时,搜索功能出了一些问题。代码看起来像这样:
conditions := make(bson.M, 0)
conditions["status"] = bson.M{"$ne": "delete"}
if item, ok := paramsPost["title"]; ok {
if item[0] != "" {
conditions["title"] = bson.RegEx{Pattern: item[0]}
}
}
if item, ok := paramsPost["from_date"]; ok {
if item[0] != "" {
conditions["publishdate"] = bson.M{}
fromDate, _ := time.Parse("2006-01-02", item[0])
conditions["publishdate"]["$gte"] = fromDate.Unix()
}
}
if item, ok := paramsPost["to_date"]; ok {
if _, ok := conditions["publishdate"]; !ok {
conditions["publishdate"] = bson.M{}
}
if item[0] != "" {
toDate, _ := time.Parse("2006-01-02", item[0])
conditions["publishdate"]["$lte"] = toDate.Unix()
}
}
然后我得到了一些错误信息:
invalid operation: conditions["publishdate"]["$gte"] (index of type interface {})
我知道我做错了什么,但是我不知道为什么,也不知道如何解决。有人可以帮助我吗?谢谢。
英文:
I'm doing a tiny project(practice) with revel and mgo, but I got something wrong with search function when I build the queries. The code seems like this:
conditions := make(bson.M, 0)
conditions["status"] = bson.M{"$ne": "delete"}
if item, ok := paramsPost["title"]; ok {
if item[0] != "" {
conditions["title"] = bson.RegEx{Pattern: item[0]}
}
}
if item, ok := paramsPost["from_date"]; ok {
if item[0] != "" {
conditions["publishdate"] = bson.M{}
fromDate, _ := time.Parse("2006-01-02", item[0])
conditions["publishdate"]["$gte"] = fromDate.Unix()
}
}
if item, ok := paramsPost["to_date"]; ok {
if _, ok := conditions["publishdate"]; !ok {
conditions["publishdate"] = bson.M{}
}
if item[0] != "" {
toDate, _ := time.Parse("2006-01-02", item[0])
conditions["publishdate"]["$lte"] = toDate.Unix()
}
}
And I got some error info:
invalid operation: conditions["publishdate"]["$gte"] (index of type interface {})
I know I make something wrong, but I don't know why, and how to resolve. Anybody can help me? Thanks
答案1
得分: 4
bson.M
是一个 map[string]interface{}
类型的变量(http://godoc.org/labix.org/v2/mgo/bson#M)。
所以,在以下代码中:
conditions["publishdate"]["$gte"] = fromDate.Unix()
当在 map 中查找 publishdate
时,你需要将 interface{}
类型断言为 bson.M
类型。
相反,你可以重构代码,改为以下形式:
publishdate := bson.M{}
// ... 在这里添加你的逻辑
conditions["publishdate"] = publishDate
这样可以避免不必要的 map 查找和类型断言。
英文:
bson.M
is a map[string]interface{}
(http://godoc.org/labix.org/v2/mgo/bson#M)
So, in
conditions["publishdate"]["$gte"] = fromDate.Unix()
You need to do a type assertion from interface{}
to bson.M
when looking up publishdate
in the map.
Instead, you could refactor the code to something like
publishdate:= bson.M{}
// ... your logic goes here
conditions["publishdate"] = publishDate
to save on unnecessary map lookups and type assertions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论