0

Go Model:

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 Data that I have:

{
    "_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"
}

My API endpoint code:

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)
}

Challenge that I am facing right now is in output, I can not see "clickCount" and "archived".

Output:

{
    "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"
        }
    ]
}

I tried changing data types to int32 and string on both fields it still didn't work. If I change the data type of these two field then in "body" of output I only see "id" and "createdAt" Let me know if more data is needed.

1 Answer 1

2

You should remove the clickCount and archived JSON tag omitempty

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked. Can you explain why this happened?
It might be linked to: golang.org/pkg/encoding/json/#Marshal -> The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.