dongyou2714 2018-03-11 22:04 采纳率: 0%
浏览 36

通过特定字段获取对象

I'm actually learning go, following some tutorial as this one to build an Resftul API app.

First time Using Go and mongoDB, I don't understand well, how to get specific key in certain document of my collection.

Actually I have this object model :

type Numobject struct {
    ID     bson.ObjectId `bson:"_id" json:"id"`
    Text   string        `bson:"text" json:"text"`
    Number int           `bson:"number" json:"number"`
    Found  bool          `bson:"found" json:"found"`
    Type   string        `bson:"type" json:"type"`
}

And I can have a specific object by ID with this function :

// Find Object by ID
func (m *NumObjectDAO) FindByNumber(id string) (Numobject, error) {
    var numObject Numobject
    err := db.C(COLLECTION).FindId(bson.ObjectIdHex(id)).One(&numObject)
    return numObject, err
}

I call my method in main.go as follow

package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "gopkg.in/mgo.v2/bson"

    . "github.com/sandaleRaclette/03-coddingChallenge/config"
    . "github.com/sandaleRaclette/03-coddingChallenge/dao"
    . "github.com/sandaleRaclette/03-coddingChallenge/models"
)

// Save the configuration of mongodatabase (localhost and which db use) in Config array
var config = Config{}
var dao = NumObjectDAO{}

// GET list of all objects
func AllObjectsEndPoint(w http.ResponseWriter, r *http.Request) {
    movies, err := dao.FindAll()
    if err != nil {
        respondWithError(w, http.StatusInternalServerError, err.Error())
        return
    }
    respondWithJson(w, http.StatusOK, movies)
}

// GET an Object by its ID
func FindObjectEndpoint(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    numObject, err := dao.FindByNumber(params["number"])
    if err != nil {
        respondWithError(w, http.StatusBadRequest, "Invalid Object ID")
        return
    }
    respondWithJson(w, http.StatusOK, numObject)
}

//  Respond Methods
func respondWithError(w http.ResponseWriter, code int, msg string) {
    respondWithJson(w, code, map[string]string{"error": msg})
}

func respondWithJson(w http.ResponseWriter, code int, payload interface{}) {
    response, _ := json.Marshal(payload)
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(code)
    w.Write(response)
}

// Parse the configuration file 'config.toml', and establish a connection to DB
func init() {
    config.Read()

    dao.Server = config.Server
    dao.Database = config.Database
    dao.Connect()
}

// Define HTTP request routes and define the differents endpoints
func main() {
    r := mux.NewRouter()
    r.HandleFunc("/api/v1/trivia", AllObjectsEndPoint).Methods("GET")
    r.HandleFunc("/api/v1/trivia/{number}", FindObjectEndpoint).Methods("GET")

    if err := http.ListenAndServe(":3000", r); err != nil {
        log.Fatal(err)
    }
}

There is other methods than getting an object by ID? How can I get an object with a specific key as Number or Type following my model ?

I want to obtain something like this when I GET "/api/v1/trivia/45000000" :

{
        "id": "5aa554c89d63b0d3580449a5",
        "text": "45000000 is the number of turkeys Americans eat at Thanksgiving annually.",
        "number": 45000000,
        "found": true,
        "type": "trivia"
    }

I'm actually looking here for some answers but I have some difficulties with query... If someone can give me beginner explanation...

  • 写回答

1条回答 默认 最新

  • dongsigan2044 2018-03-11 22:11
    关注

    Use Find for general queries:

    err := db.c(COLLECTION).Find(bson.D{{"Number", 10}}).One(&numobjecct)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?