英文:
How to write a wrapper function for FindOptions in go mongo-driver
问题
我想在我的dbobject代码中为FindOptions编写一个包装函数,这样我就可以避免在我的服务代码中导入options
包。基本上,我想在一个接口下容纳三个函数:
SetSkip()
SetLimit()
SetSort()
这样我就可以在一行代码中像这样使用Find().SetSkip().SetLimit(),这可行吗?
另外,我想了解一下MergeFindOptions的用法:
func MergeFindOptions(opts ...*FindOptions) *FindOptions
如果有示例,将非常有帮助。
英文:
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.
答案1
得分: 1
只需将options.FindOptions
结构嵌入到自定义结构中即可。此外,您可以添加一个FindOptions
函数来初始化此自定义结构,就像mongo
包通过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)
}
根据名称MergeFindOptions
和文档所说,它用于将多个FindOptions
合并为一个新的FindOptions
:
MergeFindOptions将给定的FindOptions实例合并为一个单独的FindOptions,以最后一个为准。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论