Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Clone and Copy functions in mocking MongoDB in Go?

Tags:

mongodb

go

mgo

I read this article and it has good guides for mocking MongoDB in Go. But there are some problems in Clone() and Copy() methods. I create this interfaces and structs:

type ISession interface {
    DB(name string) IDatabase
    Close()
    Clone() ISession
    Copy() ISession
}

type IDatabase interface {
    C(name string) ICollection
}

type MongoSession struct {
    dbSession *mgo.Session
}

func (s MongoSession) DB(name string) IDatabase {
    return &MongoDatabase{Database: s.dbSession.DB(name)}
}

func (s MongoSession) Clone() ISession {
    //return session.clone
    return s.dbSession.Clone()
}

func (s MongoSession) Copy() ISession {
    return s.dbSession.Copy()
}

But I got this error

cannot use s.dbSession.Clone() (type *mgo.Session) as type ISession in return argument: *mgo.Session does not implement ISession (wrong type for Clone method) have Clone() *mgo.Session want Clone() ISession

cannot use s.dbSession.Copy() (type *mgo.Session) as type ISession in return argument: *mgo.Session does not implement ISession (wrong type for Clone method) have Clone() *mgo.Session want Clone() ISession

How can I add Clone() and Copy() methods to interface?

like image 236
Vahid Jafari Avatar asked Apr 28 '18 03:04

Vahid Jafari


People also ask

How to make duplicate collection in MongoDB?

In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name.

How to copy collection from one db to another in MongoDB?

To copy a collection, you can clone it on the same database, then move the cloned collection. To clone: > use db1 switched to db db1 > db. source_collection.


1 Answers

MongoSession.Copy() and MongoSession.Clone() must return a value that implements ISession. Basically you create MongoSession type exactly for this: to implement ISession.

mgo.Session does not implement your ISession interface (e.g. because its Session.Clone() method has a return type of *mgo.Session and not ISession). You should create and return a new value of MongoSession, in which you can wrap the copied or cloned *mgo.Session value.

Like this:

func (s MongoSession) Clone() ISession {
    return MongoSession{dbSession: s.dbSession.Clone()}
}

func (s MongoSession) Copy() ISession {
    return MongoSession{dbSession: s.dbSession.Copy()}
}
like image 58
icza Avatar answered Nov 13 '22 19:11

icza