草庐IT

database - 按特定字段获取对象

coder 2024-07-09 原文

我实际上是在学习围棋,按照一些教程作为这个 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获取对象还有其他方法吗?如何根据我的模型获取具有特定键的对象作为 Number 或 Type ?

我想在 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"
    }

我实际上在寻找 here对于一些答案,但我在查询时遇到了一些困难......如果有人可以给我初学者解释......

最佳答案

使用Find一般queries :

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

关于database - 按特定字段获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49225624/

有关database - 按特定字段获取对象的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  4. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  5. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  8. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  9. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  10. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

随机推荐