为何我的更新操作返回了新结果但未能更新数据库?
时间:2024-03-21
浏览:298
作者:佚名
本文讨论了一个在执行更新操作时出现的问题,该操作返回更新后的结果,但未能更新数据库。该问题是由条件检查中的错误引起的,导致在没有错误的情况下发送内部服务器错误状态码。本文提供了解决方案,即更正条件检查以正确处理错误并更新数据库。
问题内容
我正在创建一个 restful api,并且正在创建更新函数。我使用findoneandupdate,它实际上并没有更新数据库。
我尝试了很多东西,但我对这门语言还很陌生,所以我有点迷失。
func updatecompanyendpoint(response http.responsewriter, request *http.request) {
response.header().set("content-type", "application/json")
params := mux.vars(request)
name, _ := params["name"]
var company company
_ = json.newdecoder(request.body).decode(&company)
collection := client.database("restful").collection("companies")
ctx, cancel := context.withtimeout(context.background(), 30*time.second)
defer cancel()
filter := bson.d{{"name", name}}
update := bson.d{{"$set", bson.d{{"application", company.application}}}}
err := collection.findoneandupdate(
ctx,
filter,
update).decode(&company)
if err == nil {
response.writeheader(http.statusinternalservererror)
return
}
json.newencoder(response).encode(company)
}
[
{
"name": "test1",
"application": "test1"
},
{
"name": "test2",
"application": "test2"
},
{
"name": "test3",
"application": "test3"
}
]
这是当前数据库。当我调用该函数时,它返回:
{
"name": "Test2",
"application": "Test2update"
}
但数据库保持不变。
解决方案
您的问题出在这个块中:
if err == nil {
response.WriteHeader(http.StatusInternalServerError)
return
}
json.NewEncoder(response).Encode(company)
请仔细注意,您正在发送 statusinternalservererror is err is nil,并且当 err != nil 时您会收到发布的响应,因此您的情况发生了一些错误。
到这里,我们也就讲完了《为何我的更新操作返回了新结果但未能更新数据库?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
热门专题
