转到模型:
package models
import (
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// News : News Model
type News struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Host string `json:"host,omitempty" bson:"host,omitempty"`
Category string `json:"category,omitempty" bson:"category,omitempty"`
Headline string `json:"headline,omitempty" bson:"headline,omitempty"`
Image string `json:"image,omitempty" bson:"image,omitempty"`
URL string `json:"url,omitempty" bson:"url,omitempty"`
Date string `json:"date,omitempty" bson:"date,omitempty"`
ClickCount int64 `json:"clickCount,omitempty" bson:"clickCount,omitempty"`
Archived bool `json:"archived,omitempty" bson:"archived,omitempty"`
CreatedAt time.Time `json:"createdAt,omitempty" bson:"createdAt,omitempty"`
}
我拥有的MongoDB数据:
{
"_id" : ObjectId("5e1d58f6fad87c735bbca592"),
"createdAt" : ISODate("2020-01-14T11:30:22.481Z"),
"clickCount" : 0,
"archived" : false,
"host" : "timesofindia",
"category" : "sports",
"headline" : "Caroline Wozniacki pulls out of Kooyong Classic",
"url" : "https://timesofindia.indiatimes.com/sports/tennis/top-stories/caroline-wozniacki-pulls-out-of-kooyong-classic/articleshow/73238147.cms",
"image" : "https://timesofindia.indiatimes.com/thumb/msid-73238147,width-400,resizemode-4/73238147.jpg",
"date" : "14 Jan 2020, 0958 hrs IST"
}
我的API端点代码:
func AllNews(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
collection := config.Client.Database("newspaper").Collection("news")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
var allNews []models.News
var finalResponse models.FinalResponse
cursor, e := collection.Find(ctx, bson.M{})
if e != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{ "message": "` + e.Error() + `" }`))
return
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var news models.News
cursor.Decode(&news)
allNews = append(allNews, news)
}
finalResponse.Status = "success"
finalResponse.Body = allNews
json.NewEncoder(w).Encode(finalResponse)
}
我现在面临的挑战正在输出中,我看不到“ clickCount”和“ archived”。
输出:
{
"status": "success",
"body": [
{
"_id": "5e1d58f6fad87c735bbca588",
"host": "timesofindia",
"category": "business",
"headline": "Bandhan Bank all set to announce its Q3 results today",
"image": "https://timesofindia.indiatimes.com/thumb/msid-73239715,width-400,resizemode-4/73239715.jpg",
"url": "https://timesofindia.indiatimes.com/business/india-business/bandhan-bank-all-set-to-announce-its-q3-results-today/articleshow/73239715.cms",
"date": "14 Jan 2020, 1111 hrs IST",
"createdAt": "2020-01-14T11:30:22.442Z"
}
]
}
我尝试在两个字段上将数据类型更改为int32和string,但仍然无法正常工作。如果我更改这两个字段的数据类型,那么在输出的“ body”中,我只会看到“ id”和“ createdAt”让我知道是否需要更多数据。
您应该删除clickCount
和archived
JSON标签不正确