登录
首页 >  Golang >  Go问答

返回空的fullDocument:MongoDB在插入时更改流

来源:stackoverflow

时间:2024-02-13 08:24:21 148浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《返回空的fullDocument:MongoDB在插入时更改流》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

使用 mongo 4.4 和相应的 golang 驱动程序。数据库的副本集在 localhost:27017localhost:27020 本地运行。我还尝试过使用 atlas 的沙箱集群,它给了我相同的结果。

根据 mongo 的文档,在处理插入新文档时,事件数据的 fulldocument 字段应该包含新插入的文档,但由于某种原因,我的情况并非如此。数据库和集合名称应该为 ns 字段以及存储受影响文档 _iddocumentkey 也为空。 operationtype 字段包含正确的操作类型。在另一项测试中,更新操作似乎根本不会出现在更改流中。

它曾经可以正常工作,但现在不行了。为什么会发生这种情况以及我做错了什么?

代码

// ds is the connection to discord, required for doing stuff inside handlers
func iterateChangeStream(stream *mongo.ChangeStream, ds *discordgo.Session, ctx context.Context, cancel context.CancelFunc) {
    defer stream.Close(ctx)
    defer cancel() // for graceful crashing

    for stream.Next(ctx) {
        var event bson.M
        err := stream.Decode(&event)
        if err != nil {
            log.Print(errors.Errorf("Failed to decode event: %w\n", err))
            return
        }

        rv := reflect.ValueOf(event["operationType"]) // getting operation type
        opType, ok := rv.Interface().(string)
        if !ok {
            log.Print("String expected in operationType\n")
            return
        }
        
        // event["fullDocument"] will be empty even when handling insertion
        // models.Player is a struct representing a document of the collection
        // I'm watching over
        doc, ok := event["fullDocument"].(models.Player)
        if !ok {
            log.Print("Failed to convert document into Player type")
            return
        }
        handlerCtx := context.WithValue(ctx, "doc", doc)
        // handlerToEvent maps operationType to respective handler
        go handlerToEvent[opType](ds, handlerCtx, cancel)
    }
}

func WatchEvents(ds *discordgo.Session, ctx context.Context, cancel context.CancelFunc) {

    pipeline := mongo.Pipeline{
        bson.D{{
            "$match",
            bson.D{{
                "$or", bson.A{
                    bson.D{{"operationType", "insert"}}, // !!!
                    bson.D{{"operationType", "delete"}},
                    bson.D{{"operationType", "invalidate"}},
                },
            }},
        }},
    }
    // mongo instance is initialized on program startup and stored in a global variable
    opts := options.ChangeStream().SetFullDocument(options.UpdateLookup)
    stream, err := db.Instance.Collection.Watch(ctx, pipeline, opts)
    if err != nil {
        log.Panic(err)
    }
    defer stream.Close(ctx)

    iterateChangeStream(stream, ds, ctx, cancel)
}

我的问题可能与此相关,只不过它始终发生在插入时,而不是有时发生在更新时。 如果您知道如何启用上面链接中提到的更改流优化功能标志,请告诉我。

请随时要求更多说明。


正确答案


问题已得到解答here

tldr

您需要创建以下结构来将事件解组到:

type csevent struct {
    operationtype string        `bson:"operationtype"`
    fulldocument  models.player `bson:"fulldocument"`
}
var event csevent
err := stream.decode(&event)

event 将包含插入文档的副本。

this link 中看到的示例事件中,我们可以看到 fulldocument 仅存在于 operationtype: 'insert' 上。

{ 
     _id: { _data: '825de67a42000000072b022c0100296e5a10046bbc1c6a9cbb4b6e9ca9447925e693ef46645f696400645de67a42113ea7de6472e7680004' },
    operationtype: 'insert',
    clustertime: timestamp { _bsontype: 'timestamp', low_: 7, high_: 1575385666 },
    fulldocument: { 
        _id: 5de67a42113ea7de6472e768,
        name: 'sydney harbour home',
        bedrooms: 4,
        bathrooms: 2.5,
        address: { market: 'sydney', country: 'australia' } },
        ns: { db: 'sample_airbnb', coll: 'listingsandreviews' },
        documentkey: { _id: 5de67a42113ea7de6472e768 } 
 }
 { 
    _id: { _data: '825de67a42000000082b022c0100296e5a10046bbc1c6a9cbb4b6e9ca9447925e693ef46645f696400645de67a42113ea7de6472e7680004' },
    operationtype: 'delete',
    clustertime: timestamp { _bsontype: 'timestamp', low_: 8, high_: 1575385666 },
    ns: { db: 'sample_airbnb', coll: 'listingsandreviews' },
    documentkey: { _id: 5de67a42113ea7de6472e768 } 
 }

所以我推荐你

  1. 将您的 $match 限制为 insert
  2. 或将 if 语句添加到 operationtype
      if opType == "insert" {
        doc, ok := event["fullDocument"].(models.Player)
        if !ok {
            log.Print("Failed to convert document into Player type")
            return
        }
        handlerCtx := context.WithValue(ctx, "doc", doc)
        // handlerToEvent maps operationType to respective handler
        go handlerToEvent[opType](ds, handlerCtx, cancel)
        return
      }
  1. 或者确保您使用来自 event["documentkey"]["_id"] 的文档 id 获取文档并调用 playerscollection.findone({_id: event["documentkey"]["_id"]})

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>