亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 mongo-go-driver 模擬光標

如何使用 mongo-go-driver 模擬光標

Go
海綿寶寶撒 2023-07-26 17:07:51
我剛剛學習了 go 語言,然后使用https://github.com/mongodb/mongo-go-driver與 MongoDB 和 Golang 一起制作 REST API,然后我正在進行單元測試,但在模擬 Cursor 時我陷入困境MongoDB,因為 Cursor 是一個結構,是一個想法還是有人創造了它?
查看完整描述

2 回答

?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

在我看來,模擬此類對象的最佳方法是定義一個接口,因為 go 接口是隱式實現的,您的代碼可能不需要那么多更改。一旦你有了一個界面,你就可以使用一些第三方庫來自動生成模擬,比如嘲笑


有關如何創建界面的示例


type Cursor interface{

  Next(ctx Context)

  Close(ctx Context)  

}

只需更改任何接收 mongodb 游標的函數即可使用自定義接口


查看完整回答
反對 回復 2023-07-26
?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

我剛剛遇到這個問題。因為mongo.Cursor有一個內部字段保存[]byte-- Current,為了完全模擬,您需要包裝mongo.Cursor. 以下是我為此創建的類型:


type MongoCollection interface {

    Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (MongoCursor, error)

    FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) MongoDecoder

    Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (MongoCursor, error)

}


type MongoDecoder interface {

    DecodeBytes() (bson.Raw, error)

    Decode(val interface{}) error

    Err() error

}


type MongoCursor interface {

    Decode(val interface{}) error

    Err() error

    Next(ctx context.Context) bool

    Close(ctx context.Context) error

    ID() int64

    Current() bson.Raw

}


type mongoCursor struct {

    mongo.Cursor

}


func (m *mongoCursor) Current() bson.Raw {

    return m.Cursor.Current

}

不幸的是,這將是一個移動的目標。MongoCollection隨著時間的推移,我將不得不向界面添加新功能。


查看完整回答
反對 回復 2023-07-26
  • 2 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號