我正在尝试检查MongoDB是否包含具有特定用户名和密码的数据。但现在我获取所有数据而不是指定的数据。以下是我的代码:
r.POST("/login", func(c *gin.Context) {
logedUser :=[]RegisterdUser{}
name := c.PostForm("userName")
Password := c.PostForm("userPassword")
fmt.Println("inside checking sectionnnn",name,Password)
session, err := mgo.Dial("localhost:27017")
if err != nil {
panic(err)
}
s := session.Clone()
db := s.DB("testing").C("testData")
//err = db.Find(nil).All(&logedUser)
err = db.Find(bson.M{"name": name,"password" :Password}).All(&logedUser)
//err = db.Find({"Name": name},{"Password" :Password}).All(&logedUser)
if err != nil {
log.Fatal(err)
log.Println("inside error")
}
//if logedUser !=nil{
//fmt.Println("logged")
//c.Redirect(301, "/loggedPage")
//}else{
//c.Redirect(301, "/loginError")
//}
fmt.Println("data fetched",logedUser)
c.Next()
defer session.Close()
})
我的数据库结构是:
{ "_id" : ObjectId("5a7ac6150e04b2e9c18c15af"), "name" : "aswathy", "password" : "aswathyashok" }
{ "_id" : ObjectId("5a7ad3ef0e04b2e9c18c15d1"), "name" : "anupama", "password" : "anu" }
{ "_id" : ObjectId("5a7bf0dcd90e2ccd0bd9785b"), "name" : "reema", "password" : "reemaaa" }
{ "_id" : ObjectId("5a7bf1f6d90e2ccd0bd97895"), "name" : "sreeda", "password" : "sreeda" }
内部检查部分的结果是aswath aswathyshok。
获取数据的结果是
[{aswathy aswathyashok} {anupama anu} {reema reemaaa} {sreeda sreeda} {deena deena} {farsu farsu} {beena beena} {jeena jeena}]
答案 0 :(得分:0)
据我所知,您正在寻找具体而独特的记录。如果是这样我建议只使用单个结构const data = [1,2,3,4,5,[6,7,8]]
function convert(arr) {
return arr.map(item => {
if (item instanceof Array) return convert(item);
return {id: item, clicked: false};
});
}
const mapped = convert(data);
console.log(mapped);
function flatten(arr) {
return [].concat(...arr.map(item => {
if (item instanceof Array) return flatten(item);
return [item];
}));
}
const flat = flatten(mapped);
console.log(flat)
而不是切片logedUser := RegisterdUser{}
和此方法https://godoc.org/gopkg.in/mgo.v2#Query.One,那么您将拥有logedUser :=[]RegisterdUser{}