Skip to content

上下文对象

OpContext 结构体用于传递操作上下文信息,它包含以下字段:

go
type OpContext struct {
    Col    *mongo.Collection `opt:"-"`
    Fields []*field.Filed

    Doc any
    // filter also can be used as query
    Filter       any
    Updates      any
    Pipeline     any
    MongoOptions any
    ModelHook    any
    ReflectValue reflect.Value
    StartTime    time.Time

    // result of the collection operation
    Result any
}

结构体字段说明:

  • Col*mongo.Collection 对象
  • Fields[]*field.Filed 对象,存储的是 Collection 对象所绑定泛型的结构体字段元数据。
  • Doc:文档对象,为 Collection 对象所绑定泛型的结构体对象,例如 *T[]*T
  • Filter:查询条件。
  • Updates:更新文档。
  • Pipeline:聚合管道。
  • MongoOptionsmongo 操作选项。
  • ModelHook:模型钩子。
  • ReflectValue:为 Doc 的反射值,可用于在插件里动态修改文档对象。
  • StartTime:操作开始时间。
  • Resultmongo collection 操作的结果。

不同的操作类型,OpContext 的字段值可能不同,例如:

  • opTypeoperation.OpTypeBeforeInsertoperation.OpTypeAfterInsert 时:

    • opCtx.Doc 的值可能不为 nil,其类型可能是 *struct[]*struct
    • opCtx.ReflectValue 的值不为 nil
  • opTypeoperation.OpTypeBeforeUpdateoperation.OpTypeAfterUpdate 时:

    • opCtx.FilteropCtx.Updates 的值可能不为 nil
  • opTypeoperation.OpTypeBeforeDeleteoperation.OpTypeAfterDelete 时:

    • opCtx.Filter 的值可能不为 nil
  • opTypeoperation.OpTypeBeforeUpsertoperation.OpTypeAfterUpsert 时:

    • opCtx.FilteropCtx.Updates 的值可能不为 nil
  • opTypeoperation.OpTypeBeforeFindoperation.OpTypeAfterFind 时:

    • opCtx.Filter 的值可能不为 nil
    • 如果类型是后者,opCtx.Doc 的值可能不为 nil
    • opCtx.Result 的值可能不为 nil
  • opTypeoperation.OpTypeBeforeAnyoperation.OpTypeAfterAny 时,OpContext 的所有字段值参考上述说明。

  • 无论是哪种操作类型,OpContextColFields 以及 StartTime 的值都不为 nil

  • 无论是哪种操作类型,OpContextopCtx.MongoOptionsopCtx.Result 的值可能不为 nil

  • OpContextMongoOptionsModelHook 是否为 nil,取决于在执行 MongoDB 操作时,使用者是否通过 CreatorUpdaterDeleterFinderAggregator 设置它们。