我有一個簡單的 CRUDbook應用程式
golang,mongo-go-driver
想要:將每個 CRUD 操作記錄到單個集合中。
例如:
- 創建一本書
- 將書插入
book收藏 - 使用, .. 等將
book.created事件插入到history集合中bookIdtimestamp
問題:
- 想知道實作此功能的推薦方法是什么?
- 里面有
hook特色mongo-go-driver嗎?(鉤子將在集合上的更新事件上觸發......等)
uj5u.com熱心網友回復:
這是目前不支持的,如果您考慮一下,插入和更新可能不會發生在驅動程式級別,而是發生在資料庫本身(例如,聚合結果可能會“轉儲”到集合中)。
相反,您可以查看MongoDB 資料庫本身支持的更改流。您可以“訂閱”更改事件,當發生更改操作時,您會收到通知。
這與所問的不完全相同,因為更改的來源(或原因)可能不是來自您的應用程式,因此這對您來說可能是也可能不是優勢。
您可以使用該Collection.Watch()方法訂閱集合的更改。以下是檔案中如何訂閱并獲得“插入”操作通知的示例:
var collection *mongo.Collection
// Specify a pipeline that will only match "insert" events.
// Specify the MaxAwaitTimeOption to have each attempt wait two seconds for
// new documents.
matchStage := bson.D{{"$match", bson.D{{"operationType", "insert"}}}}
opts := options.ChangeStream().SetMaxAwaitTime(2 * time.Second)
changeStream, err := collection.Watch(
context.TODO(),
mongo.Pipeline{matchStage},
opts)
if err != nil {
log.Fatal(err)
}
// Print out all change stream events in the order they're received.
// See the mongo.ChangeStream documentation for more examples of using
// change streams.
for changeStream.Next(context.TODO()) {
fmt.Println(changeStream.Current)
}
您可以從MongoDB 檔案訂閱支持的操作串列:
insertdeletereplaceupdatedroprenamedropDatabaseinvalidate
uj5u.com熱心網友回復:
我對 Go 本身并不熟悉,但一般的 mongo(客戶端)方法是命令監控,我認為 go 驅動程式也支持。您可以在此處和此處閱讀有關它的內容。你需要的事件是CommandSucceededEvent
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354245.html
