gpt4 book ai didi

mongodb - 我们如何在golang中编写条件?

转载 作者:数据小太阳 更新时间:2023-10-29 03:22:28 25 4
gpt4 key购买 nike

我在 Controller 部分编写查询,但根据 MVC 结构,逻辑在模型中, Controller 部分仅用于发送数据,所以过去我使用如下条件:-

models.Retrieve(bson.M{"_id": Id, "is_deleted": false})

//fucntion for this query is
fucn Retrieve(query interface{}){

// do stuff

}

但是现在上面的查询将使用映射进行更改,我正在编写一个函数以将其用于多种目的以检索数据,例如:-

conditions := make(map[string]interface{})
conditions["operator1"] = "_id"
codnitions["value1"] = id
conditions["operator2"] = "is_deleted"
conditions["value2"] = false

func Retrieve(data map[string]interface{}){

//queries here

}

有人告诉我这是正确的方法。如果是,请告诉我怎么做?

如果不是,能否请您告诉我一个例子或适合我的问题的答案。

已编辑:-

这个函数也用于“代码”的查找方式models.Retrieve(bson.M{"code": Code, "is_deleted": false})

也可以这样写:-

conditions := make(map[string]interface{})
conditions["operator1"] = "code"
codnitions["value1"] = Code
conditions["operator2"] = "is_deleted"
conditions["value2"] = false

提前致谢。

最佳答案

如果我理解正确,您需要一个能够处理不同键值对作为查询输入的函数。我在 Go 中实现如下:

type UserResolver int

// String satisfies the Stringer interface
func (ur UserResolver) String() string {
strs := [...]string {
"ID",
"Code",
}
// return empty string if index out of bounds
if int(ur) >= len(strs) {
return ""
}
return strs[ur]
}

// Add any required functions to UserResolver that you may require,
// such as schemaKey() that returns the specified schema key value:
// In your example case "_id", "Code", "is_deleted", etc.

const (
ID UserResolver = iota
Code
)

func ResolveUser(by UserResolver, value interface{}) (User, error) {
if by.String() == "" {
return nil, fmt.Errorf("Unknown UserResolver specified")
}

if value == nil {
return nil, fmt.Errorf("Nil value provided, unable to resolve User")
}

// Query details here:
// It will be specific to your persistence model and remember to follow the
// best practices for your specific db, such as properly escaping inputs...

return User, nil
}

这种方法通过使用可以导出或不导出(根据您的 API 设计)的附加函数来扩展 UserResolver 功能,从而为您提供了极大的灵 active 。它基本上使用 iota(自动枚举)将各种选项映射到具有在 const 部分中定义的公共(public)索引的 slice 。您现在可以添加使用 switch 语句来执行类型或条件特定工作的函数。

该函数现在可以被其他包调用,如下所示:

u, err := ResolveUser(user.ID, uid)
if err != nil {
return fmt.Errorf(
"User not found! Unable to obtain user by %s = %v",
user.ID,
uid,
)
}

条件部分可以类似地实现,然后在查找索引和查找条件之间适本地分开。

关于mongodb - 我们如何在golang中编写条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com