我正在使用 Golang/Fiber + Mongo 驱动程序。
我有一个简单的博客文章结构:
type Post struct {
ID primitive.ObjectID `json:"_id" bson:"_id,omitempty"`
Title *string `json:"title" bson:"title"`
Slug *string `json:"slug" bson:"slug"`
Content []interface{} `json:"content" bson:"content,omitempty"` // same as any[]
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
PublishedAt *time.Time `json:"published_at" bson:"published_at"`
}
在内容中,我放置了对象数组:
[
{
data: 'blah blah'
},
{
data: 'blah blah'
}
]
方法本身非常简单:
func GetPostBySlug(slug string) (Post, error) {
post := Post{}
filter := bson.M{
"slug": slug,
}
database, error := Database.GetMongoDatabase()
if error != nil {
println(error)
}
collection := database.Collection(model_name)
err := collection.FindOne(ctx, filter).Decode(&post)
if err != nil {
return post, err
}
return post, nil
}
这就是我得到的:
"_id": "000000000000000000000000",
"title": "Test",
"slug": "test",
"content": [ // array of arrays? what??
[
{
"Key": "data",
"Value": "blah blah"
},
{
"Key": "data",
"Value": "blah blah"
},
]
],
"created_at": "2022-06-07T21:08:04.261Z",
"updated_at": "2022-07-20T21:42:36.717Z",
"published_at": null
在 mongodb 中,内容字段完全按照我传递的方式保存,但是当我尝试获取文档时,内容会转换为这个带有键值对的奇怪数组。
如果我保存如下内容:
content: [
{
data: {
test: 'test',
what: 'what'
}
}
]
它将转换为:
content: [
[
Key: "data",
Value: [
{
Key: "test",
Value: "test"
},
{
Key: "what",
Value: "what"
},
]
]
]
我理解这背后的原因(这只是 golang 处理 JSON 的方式?)并假设中间某处应该有一个额外的步骤,但我不知道我到底需要做什么
慕盖茨4494581
qq_花开花谢_0
蝴蝶不菲
相关分类