今天偶然间发现,使用go的第三方包调用mongo
1、如果是One()找一条记录的话,如果找不到,回返回ErrNotFound这个错误
2、但是如果是All()的话,找很多条记录,就算找不到,也不会返回任何错误
验证代码如下:
package main
import (
"fmt"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
)
type Student struct{
Name string `bson:"name"`
age uint32 `bson:"age"`
}
func main(){
session,err:=mgo.Dial("127.0.0.1:27017")
if err!=nil{
fmt.Println("err=",err)
}
session.SetMode(mgo.Monotonic,true)
db:=session.DB("test")
collection:=db.C("student")
stu:=&Student{}
err=collection.Find(bson.M{"name":"随便乱输"}).One(&stu)
if err!=nil{
fmt.Println("err=",err)
fmt.Println(err==mgo.ErrNotFound)
}
fmt.Printf("%+v",stu)
stus:=make([]*Student,0)
err2:=collection.Find(bson.M{"name":"随便乱输"}).All(&stus)
if err2!=nil{
fmt.Println("err2=",err2)
}
fmt.Printf("%+v",stus)
}
输出结果:
从结果可以看出,如果是One()操作找不到返回错误,如果是All()操作,找不到不会返回错误