How to use Exists method of mgo Package

Best Keploy code snippet using mgo.Exists

models.go

Source:models.go Github

copy

Full Screen

...30 Code string `bson:"code"`31 Lang string `bson:"lang"`32 WaitDays int `bson:"waitdays"`33}34func AdminExists(s *mgo.Session, email string, pwd string) bool {35 var coll = s.DB("admin").C("admin");36 num,err := coll.Find(bson.M{"email": email, "pass": pwd}).Count();37 if err!=nil {38 println(err.Error())39 }40 if num == 1 {41 return true;42 }43 return false;44}45func AdminRoot(s *mgo.Session, email string) bool {46 var coll = s.DB("admin").C("admin");47 num,err := coll.Find(bson.M{"email": email, "isroot":true}).Count();48 if err!=nil {49 println(err.Error())50 }51 if num== 1 {52 return true;53 }54 return false;55}56func Collection(s *mgo.Session) *mgo.Collection {57 return s.DB("").C("")58}59func AllAdmins(s *mgo.Session) []Admin {60 var coll = s.DB("admin").C("admin");61 var admins []Admin62 coll.Find(nil).All(&admins)63 return admins;64}65func CustomersCount(s *mgo.Session) int {66 n,e := s.DB("richwallet").C("wallet").Count()67 if e!=nil {68 println(e.Error())69 }70 return n;71}72func AuthUser(s *mgo.Session) []Customer {73 var customers []Customer;74 s.DB("richwallet").C("wallet").Find(bson.M{"authKey":bson.M{"$exists":true}}).All(&customers)75 return customers76}77func AllCustomers(s *mgo.Session) []Customer {78 var customers []Customer;79 s.DB("richwallet").C("wallet").Find(nil).All(&customers)80 return customers81}82func CustomerPage(s *mgo.Session, frompage int ,pagesize int)[]Customer {83 var customers []Customer;84 s.DB("richwallet").C("wallet").Find(nil).Skip(frompage*pagesize).85 Limit(pagesize).All(&customers);86 return customers87}88func DeleteAuth(s *mgo.Session, email string) ([]Customer){89 colQuerier := bson.M{"email": email}90 unset := bson.M{"authKey": bson.M{"$exists":true}}91 change := bson.M{"$unset": unset}92 err := s.DB("richwallet").C("wallet").Update(colQuerier, change)93 if err != nil {94 panic(err)95 }96 println("delete auth "+ email)97 var customer []Customer98 s.DB("richwallet").C("wallet").Find(bson.M{"authKey":bson.M{"$exists":true}}).All(&customer)99 return customer100}101func SearchCustomers(s *mgo.Session, email string) []Customer {102 var customers []Customer;103 s.DB("richwallet").C("wallet").Find(bson.M{"email":email}).All(&customers)104 return customers105}106func SearchAuthCustomers(s *mgo.Session, email string) []Customer {107 var customers []Customer;108 s.DB("richwallet").C("wallet").Find(bson.M{"email":email, "authKey":bson.M{"$exists":true}}).All(&customers)109 return customers110}111func AddAdmin(s *mgo.Session, email string, pass string) bool {112 count,_ := s.DB("admin").C("admin").Find(bson.M{"email":email}).Count()113 114 if count>0 {115 println("create duplicate")116 return false;117 }118 s.DB("admin").C("admin").Insert(bson.M{"email": email, "pass": pass});119 return true;120}121func DeleteAdmin(s *mgo.Session, email string) ([]Admin, bool) {122 count,_ := s.DB("admin").C("admin").Find(bson.M{"email":email, "isroot":true}).Count()123 var deleted = false;124 if count>0 {125 panic("root only have one");126 } else {127 s.DB("admin").C("admin").Remove(bson.M{"email": email});128 deleted = true129 }130 var admins []Admin;131 s.DB("admin").C("admin").Find(nil).All(&admins);132 return admins, deleted133}134func EditAdminEmail(s *mgo.Session, srcemail string, dstemail string) (string ,error) {135 count,_ := s.DB("admin").C("admin").Find(bson.M{"email":dstemail}).Count()136 if count > 0 {137 return "",errors.New(" dst email exists");138 }139 140 err := s.DB("admin").C("admin").Update(bson.M{"email":srcemail}, bson.M{"$set": bson.M{"email":dstemail}});141 if err!=nil {142 panic(err.Error())143 }144 return dstemail, err145}146func EditAdminPass(s *mgo.Session, srcemail string, newpass string) (string ,error) {147 count,_ := s.DB("admin").C("admin").Find(bson.M{"email":srcemail}).Count()148 if count == 0 {149 return "",errors.New("email doesnot exists");150 }151 152 err := s.DB("admin").C("admin").Update(bson.M{"email":srcemail}, bson.M{"$set": bson.M{"pass": newpass}});153 if err!=nil {154 panic(err.Error())155 }156 return newpass, err157}158/*************************************************************159 * 功能-- 160 * 场景-- 161 * 依赖--162 **************************************************************/163func EditAuth(s *mgo.Session, srcemail string, authKey string) (string ,error) {164 count,_ := s.DB("richwallet").C("wallet").Find(bson.M{"email":srcemail}).Count()165 if count == 0 {166 return "",errors.New("email doesnot exists");167 }168 var err error;169 if authKey == "" {170 DeleteAuth(s, srcemail);171 } else {172 err = s.DB("richwallet").C("wallet").Update(bson.M{"email":srcemail}, bson.M{"$set": bson.M{"authKey": authKey}});173 if err!=nil {174 println(err.Error())175 }176 }177 return authKey, err178}179func AllResetPetitioners(s *mgo.Session) []RequestCancelAuthCs{180 var all []RequestCancelAuthCs 181 err := s.DB("richwallet").C("reset_auth").Find(nil).All(&all)182 if err!=nil {183 println(err.Error())184 }185 return all186}187func AddRequestResetAuth(s *mgo.Session, email string, code string) (error, bool) {188/*************************************************************189 * 功能-- add the user who requested to reset auth190 * 场景-- 用户发送请求重置 Auth191 * 依赖--192 * 逻辑-- 判断是否曾经提交过, 判断上次提交是否已经超时193 **************************************************************/194 var result RequestCancelAuthCs;195 query := s.DB("richwallet").C("reset_auth").Find(bson.M{"email": email})196 err := query.Sort("-reqTime").One(&result)197 if err!=nil {198 return s.DB("richwallet").C("reset_auth").Insert(bson.M{"email":email, 199 "reqTime":time.Now(), 200 "state": "emailsent",201 "code": code}), false202 }203 204 if result.State == "expired" || result.State== "processed" {205 return s.DB("richwallet").C("reset_auth").Update(bson.M{"email":email},206 bson.M{"$set": bson.M{"reqtime":time.Now(), "code": code, "state": "emailsent"}}) , false} else {207 return errors.New("update fails"), true;208 }209}210func SetSentEmail(s *mgo.Session, email string) error {211 return s.DB("richwallet").C("reset_auth").Update(bson.M{"email":email}, bson.M{"$set": bson.M{"state":"emailsent"}})212}213func ReqTime(s *mgo.Session, email string) time.Time {214 var result RequestCancelAuthCs 215 err := s.DB("richwallet").C("reset_auth").Find(bson.M{"email":email}).One(& result)216 if err!=nil {217 println(err.Error())218 return time.Now()219 } else {220 return result.ReqTime221 }222}223func SetAuthState(s *mgo.Session, email string, state string) error {224 return s.DB("richwallet").C("reset_auth").Update(bson.M{"email":email}, bson.M{"$set": bson.M{"state": state}})225}226func SetAuthValidate(s *mgo.Session, email string) error {227 return s.DB("richwallet").C("reset_auth").Update(bson.M{"email":email}, bson.M{"$set": bson.M{"state":"emailchecked"}})228}229//unc SetAuthFrozenAccount(s *mgo.Session, email string, value bool) error {230// return s.DB("richwallet").C("reset_auth").Update(bson.M{"email":email }, bson.M{"$set": bson.M{"state":value}})231//232func SetAuthProcessed(s *mgo.Session, email string) error {233 println("set auth processed:" + email)234 return s.DB("richwallet").C("reset_auth").Update(bson.M{"email":email, "state": "emailchecked"}, bson.M{"$set": bson.M{"email":email, "state":"processed"}})235}236//237func SetAuthTimeout(s *mgo.Session, email string) error {238 println("set auth timeout:" + email)239 return s.DB("richwallet").C("reset_auth").Update(bson.M{"email":email}, bson.M{"$set": bson.M{"state": "expired"}})240}241func IsAuthUserExists(s *mgo.Session, email string, serverKey string) bool {242 var coll = s.DB("richwallet").C("wallet");243 num,err := coll.Find(bson.M{"email": email, "serverKey":serverKey, "authKey": bson.M{"$exists" : true} }).Count();244 if err!=nil {245 println(err.Error())246 }247 if num >= 1 {248 return true;249 }250 return false;251}252func AddVerfiedCode(s *mgo.Session, email string, serverKey string, code string) bool {253/*************************************************************254 * 功能--255 * 场景--...

Full Screen

Full Screen

mongo.go

Source:mongo.go Github

copy

Full Screen

1package db2import (3 "errors"4 "fmt"5 "sync"6 "time"7 "github.com/coralproject/shelf/internal/platform/db/mongo"8 "gopkg.in/mgo.v2"9 "gopkg.in/mgo.v2/bson"10)11// Multiple master sessions can be created for different databases. Each master12// session must be registered first. A new copy of the master session can be13// acquired. The session is provided through the DB type value.14// ErrInvalidDBProvided is returned in the event that an uninitialized db is15// used to perform actions against.16var ErrInvalidDBProvided = errors.New("Invalid DB provided")17//==============================================================================18// mgoDB maintains a master session for a given database.19type mgoDB struct {20 ses *mgo.Session21}22// masterMGO manages a set of different MongoDB master sessions.23var masterMGO = struct {24 sync.RWMutex25 ses map[string]mgoDB26}{27 ses: make(map[string]mgoDB),28}29// RegMasterSession adds a new master session to the set. If no url is provided,30// it will default to localhost:27017.31func RegMasterSession(context interface{}, name string, url string, timeout time.Duration) error {32 masterMGO.Lock()33 defer masterMGO.Unlock()34 if _, exists := masterMGO.ses[name]; exists {35 return errors.New("Master session already exists")36 }37 ses, err := mongo.New(url, timeout)38 if err != nil {39 return err40 }41 masterMGO.ses[name] = mgoDB{42 ses: ses,43 }44 return nil45}46//==============================================================================47// Factory function for acquiring a copy of a session.48// NewMGO returns a new DB value for use with MongoDB based on a registered49// master session.50func NewMGO(context interface{}, name string) (*DB, error) {51 var db mgoDB52 var exists bool53 masterMGO.RLock()54 {55 db, exists = masterMGO.ses[name]56 }57 masterMGO.RUnlock()58 if !exists {59 return nil, fmt.Errorf("Master sesssion %q does not exist", name)60 }61 ses := db.ses.Copy()62 // As per the mgo documentation, https://godoc.org/gopkg.in/mgo.v2#Session.DB63 // if no database name is specified, then use the default one, or the one that64 // the connection was dialed with.65 mdb := ses.DB("")66 dbOut := DB{67 database: mdb,68 session: ses,69 }70 return &dbOut, nil71}72//==============================================================================73// Methods for the DB struct type related to MongoDB.74// CloseMGO closes a DB value being used with MongoDB.75func (db *DB) CloseMGO(context interface{}) {76 db.session.Close()77}78// ExecuteMGO is used to execute MongoDB commands.79func (db *DB) ExecuteMGO(context interface{}, colName string, f func(*mgo.Collection) error) error {80 if db == nil || db.session == nil {81 return ErrInvalidDBProvided82 }83 return f(db.database.C(colName))84}85// ExecuteMGOTimeout is used to execute MongoDB commands with a timeout.86func (db *DB) ExecuteMGOTimeout(context interface{}, timeout time.Duration, colName string, f func(*mgo.Collection) error) error {87 if db == nil || db.session == nil {88 return ErrInvalidDBProvided89 }90 db.session.SetSocketTimeout(timeout)91 return f(db.database.C(colName))92}93// BatchedQueryMGO returns an iterator capable of iterating over94// all the results of a query in batches.95func (db *DB) BatchedQueryMGO(context interface{}, colName string, q bson.M) (*mgo.Iter, error) {96 if db == nil || db.session == nil {97 return nil, ErrInvalidDBProvided98 }99 c := db.database.C(colName)100 return c.Find(q).Iter(), nil101}102// BulkOperationMGO returns a bulk value that allows multiple orthogonal103// changes to be delivered to the server.104func (db *DB) BulkOperationMGO(context interface{}, colName string) (*mgo.Bulk, error) {105 if db == nil || db.session == nil {106 return nil, ErrInvalidDBProvided107 }108 c := db.database.C(colName)109 tx := c.Bulk()110 tx.Unordered()111 return tx, nil112}113// CollectionMGO is used to get a collection value.114func (db *DB) CollectionMGO(context interface{}, colName string) (*mgo.Collection, error) {115 if db == nil || db.session == nil {116 return nil, ErrInvalidDBProvided117 }118 return db.database.C(colName), nil119}120// CollectionMGOTimeout is used to get a collection value with a timeout.121func (db *DB) CollectionMGOTimeout(context interface{}, timeout time.Duration, colName string) (*mgo.Collection, error) {122 if db == nil || db.session == nil {123 return nil, ErrInvalidDBProvided124 }125 db.session.SetSocketTimeout(timeout)126 return db.database.C(colName), nil127}...

Full Screen

Full Screen

Exists

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 session, err := mgo.Dial("localhost")4 if err != nil {5 panic(err)6 }7 defer session.Close()8 session.SetMode(mgo.Monotonic, true)9 c := session.DB("test").C("people")10 count, err := c.Count()11 if err != nil {12 panic(err)13 }14 fmt.Println("Count:", count)15}

Full Screen

Full Screen

Exists

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 panic(err)5 }6 defer session.Close()7 session.SetMode(mgo.Monotonic, true)8 c := session.DB("test").C("test")9 if exists, err := c.Exists(); exists {10 fmt.Println("Collection exists")11 } else {12 fmt.Println("Collection does not exist")13 }14}15func (c *Collection) Find(query interface{}) *Query16import (17type Person struct {18}19func main() {20 if err != nil {21 panic(err)22 }23 defer session.Close()24 session.SetMode(mgo.Monotonic, true)25 c := session.DB("test").C("test")26 result := Person{}27 err = c.Find(nil).One(&result)28 if err != nil {29 fmt.Println(err)30 }31 fmt.Println("Phone:", result.Phone)32}33func (c *Collection) FindId(id interface{}) *Query34import (35type Person struct {

Full Screen

Full Screen

Exists

Using AI Code Generation

copy

Full Screen

1func main() {2 session, err := mgo.Dial("localhost")3 if err != nil {4 panic(err)5 }6 defer session.Close()7 session.SetMode(mgo.Monotonic, true)8 c := session.DB("test").C("people")9 count, err := c.Find(bson.M{"name": "Ale"}).Count()10 if err != nil {11 panic(err)12 }13 fmt.Println("Count:", count)14}15func main() {16 session, err := mgo.Dial("localhost")17 if err != nil {18 panic(err)19 }20 defer session.Close()21 session.SetMode(mgo.Monotonic, true)22 c := session.DB("test").C("people")23 result := Person{}24 err = c.Find(bson.M{"name": "Ale"}).One(&result)25 if err != nil {26 panic(err)27 }28 fmt.Println("Phone:", result.Phone)29}30func main() {31 session, err := mgo.Dial("localhost")32 if err != nil {33 panic(err)34 }35 defer session.Close()36 session.SetMode(mgo.Monotonic, true)37 c := session.DB("test").C("people")38 result := Person{}39 err = c.FindId(bson.ObjectIdHex("4f4c4d4e4f4d4e4f4f4d4e4f")).One(&result)40 if err != nil {41 panic(err)42 }43 fmt.Println("Phone:", result.Phone)44}

Full Screen

Full Screen

Exists

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 panic(err)5 }6 defer session.Close()7 db := session.DB("test")8 collection := db.C("test")9 result := bson.M{}10 err = collection.Find(bson.M{"name": "test"}).One(&result)11 if err != nil {12 if err == mgo.ErrNotFound {13 fmt.Println("not found")14 }15 }16 fmt.Println(result)17}18import (19func main() {20 if err != nil {21 panic(err)22 }23 defer session.Close()24 db := session.DB("test")25 collection := db.C("test")26 result := bson.M{}27 err = collection.Find(bson.M{"name": "test"}).One(&result)28 if err != nil {29 if err == mgo.ErrNotFound {30 fmt.Println("not found")31 }32 }33 fmt.Println(result)34}

Full Screen

Full Screen

Exists

Using AI Code Generation

copy

Full Screen

1import ( 2func main() { 3 session, err := mgo.Dial("localhost:27017")4 if err != nil {5 panic(err)6 }7 defer session.Close()8 session.SetMode(mgo.Monotonic, true)9 c := session.DB("test").C("people")10 fmt.Println(c.Exists())11}

Full Screen

Full Screen

Exists

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 session, err = mgo.Dial("localhost")4 if err != nil {5 panic(err)6 }7 defer session.Close()8 session.SetMode(mgo.Monotonic, true)9 c := session.DB("test").C("user")10 var result map[string]interface{}11 err = c.Find(nil).One(&result)12 if err != nil {13 panic(err)14 }15 fmt.Println("Result: ", result)16}

Full Screen

Full Screen

Exists

Using AI Code Generation

copy

Full Screen

1if mgo.Exists("CollectionName", bson.M{"key": "value"}) {2}3if !mgo.Exists("CollectionName", bson.M{"key": "value"}) {4}5if mgo.Exists("CollectionName", bson.M{"key": "value"}, bson.M{"key": "value"}) {6}7if !mgo.Exists("CollectionName", bson.M{"key": "value"}, bson.M{"key": "value"}) {8}9if mgo.Exists("CollectionName", bson.M{"key": "value"}, bson.M{"key": "value"}, bson.M{"key": "value"}) {10}11if !mgo.Exists("CollectionName", bson.M{"key": "value"}, bson.M{"key": "value"}, bson.M{"key": "value"}) {12}13if mgo.Exists("CollectionName", bson.M{"key": "value"}, bson.M{"key": "value"}, bson.M{"key": "value"}, bson.M{"key": "value"}) {14}15if !mgo.Exists("CollectionName", bson.M{"key": "value"}, bson.M{"key": "value"}, bson.M{"key": "value"}, bson.M{"key": "value"}) {16}

Full Screen

Full Screen

Exists

Using AI Code Generation

copy

Full Screen

1if !mgo.Exists("1") {2 mgo.Insert("1", "1")3}4if !mgo.Exists("2") {5 mgo.Insert("2", "2")6}7if !mgo.Exists("3") {8 mgo.Insert("3", "3")9}10if !mgo.Exists("4") {11 mgo.Insert("4", "4")12}13if !mgo.Exists("5") {14 mgo.Insert("5", "5")15}16if !mgo.Exists("6") {17 mgo.Insert("6", "6")18}19if !mgo.Exists("7") {20 mgo.Insert("7", "7")21}22if !mgo.Exists("8") {23 mgo.Insert("8", "8")24}25if !mgo.Exists("9") {26 mgo.Insert("9", "9")27}28if !mgo.Exists("10") {29 mgo.Insert("10", "10")30}31if !mgo.Exists("11") {32 mgo.Insert("11", "11")33}34if !mgo.Exists("12") {35 mgo.Insert("12", "12")36}37if !mgo.Exists("13") {38 mgo.Insert("13", "13")39}40if !mgo.Exists("14") {41 mgo.Insert("14", "14")42}43if !mgo.Exists("15") {44 mgo.Insert("15", "15")45}46if !mgo.Exists("16") {47 mgo.Insert("16", "16")48}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Keploy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful