Search code examples
mongodbgomongodb-querydrivergolang-migrate

How to write a wrapper function for FindOptions in go mongo-driver


I want to write a wrapper function for FindOptions in my dbobject code so that I can avoid importing package options in my service code . Basically i'm trying to accomodate three func under one interface

SetSkip() 
SetLimit()
SetSort()

so that i should be able to do something like Find().SetSkip().SetLimit() in a single line , is that doable ?

Also I want to know the usage of MergeFindOptions

func MergeFindOptions(opts ...*FindOptions) *FindOptions

Any examples will be of great help.


Solution

  • Just embed the options.FindOptions struct into a custom one. Additionally you could add a FindOptions function to initialize this custom struct, like the mongo package do by options.Find().

    package your_db_package
    
    type YourFindOptions struct {
        *options.FindOptions
    }
    
    func FindOptions() YourFindOptions {
        return YourFindOptions{options.Find()}
    }
    
    // ---
    package your_service_package
    
    import "your_db_package"
    
    func GetItems() {
      opts := your_db_package.FindOptions().SetSkip(123).SetLimit(456)
    } 
    

    As the name MergeFindOptions and the documentation says it's for merging multiple FindOptions into a new one:

    MergeFindOptions combines the given FindOptions instances into a single FindOptions in a last-one-wins fashion.