按特定字段

时间:2018-03-11 22:04:29

标签: database mongodb go

我实际上正在学习go,按照这个one的一些教程来构建Resftul API应用程序。

第一次使用Go和mongoDB,我不太了解,如何在我的收藏的某些文件中获取特定的密钥。

其实我有这个对象模型:

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"`
}

我可以通过ID使用此函数获得特定对象:

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

我在main.go中调用我的方法如下

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

除了通过ID获取对象之外还有其他方法吗?如何在模型后面获取具有特定键的对象作为数字或类型?

当我获得“/ api / v1 / trivia / 45000000”时,我希望得到类似的东西:

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

我实际上正在寻找here的答案,但我在查询方面遇到了一些困难...如果有人能给我初学者解释......

1 个答案:

答案 0 :(得分:0)

Find用于一般queries

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