【发布时间】:2018-09-12 17:59:24
【问题描述】:
当用户点击http://localhost:8080/api/v1/customer?keyword=dhiman 之类的网址时,我正在从数据库中检索数据,然后如果有任何字段匹配,它将在集合中搜索数据,然后它将检索该数据。如果用户输入像http://localhost:8080/api/v1/customer?keyword=dhi 这样的短网址,那么它也会检索匹配的数据,我将如何解决这个问题。我尝试了如下代码:-
客户结构
type Customer struct {
Id int `json:"id" bson:"_id"`
FirstName string `json:"first_name" bson:"first_name"`
LastName string `json:"last_name" bson:"last_name"`
Email string `json:"email" bson:"email"`
PhoneNumber string `json:"phone_number" bson:"phone_number"`
}
type Customers []Customer
功能
func GetCustomers(c *gin.Context) {
value := c.Query("keyword")
fmt.Println(value)
response := ResponseControllerList{}
conditions := bson.M{"last_name":value}
data, err := models.GetCustomerListing(conditions)
if err != nil {
response = ResponseControllerList{
config.FailureCode,
config.FailureFlag,
config.FailureMsg,
nil,
nil,
}
} else {
response = ResponseControllerList{
config.SuccessFlag,
config.SuccessFlag,
config.SuccessMsg,
data,
// dataCount,
nil,
}
}
GetResponseList(c, response)
}
模型页面中的GetCustomerListing函数:-
func GetCustomerListing(customerQuery interface{}) (result Customers, err error) {
mongoSession := config.ConnectDb()
sessionCopy := mongoSession.Copy()
defer sessionCopy.Close()
getCollection := mongoSession.DB(config.Database).C(config.CustomerCollection)
err = getCollection.Find(customerQuery).Select(bson.M{"password": 0}).All(&result) //.Skip(skip).Limit(limit)
if err != nil {
return result, err
}
return result, nil
}
收藏图片
【问题讨论】:
-
您遇到了什么问题/错误?
Customers类型的定义是什么? -
@icza 我编辑我的问题
-
它在用户输入姓氏时检索数据,但如果它输入名字,那么它不会检索我想要的数据如果用户输入任何字段数据,那么它会检索与它匹配的数据例如
http://localhost:8080/api/v1/customer?keyword=puneet然后它与集合first_name匹配并检索它@icza -
这个问题看起来可以这样写:“在 mongodb 中我如何查询、多个字段和/或执行 SQL LIKE 过滤器”。如果这是问题,只需查询 SO 就会得到答案。问题的 URL 和网络似乎不相关。