11

Go を使用して MongoDB にデータを挿入しようとしています。

データ構造は次のとおりです。

type Entry struct {
    Id          string `json:"id",bson:"_id,omitempty"`
    ResourceId  int    `json:"resource_id,bson:"resource_id"`
    Word        string `json:"word",bson:"word"`
    Meaning     string `json:"meaning",bson:"meaning"`
    Example     string `json:"example",bson:"example"`
}

これは私の挿入機能です:

func insertEntry(db *mgo.Session, entry *Entry) error {
    c := db.DB(*mongoDB).C("entries")
    count, err := c.Find(bson.M{"resourceid": entry.ResourceId}).Limit(1).Count()
    if err != nil {
        return err
    }
    if count > 0 {
        return fmt.Errorf("resource %s already exists", entry.ResourceId)
    }
    return c.Insert(entry)
}

そして最後に、これは私がそれを呼び出す方法です:

entry := &Entry{
    ResourceId:  resourceId,
    Word:        word,
    Meaning:     meaning,
    Example:     example,
}
err = insertEntry(db, entry)
if err != nil {
    log.Println("Could not save the entry to MongoDB:", err)
}

問題は、bsonタグが魔法のように機能することを期待していたのですが、そうではありません。データが次のように保存される代わりに:

{ "_id" : ObjectId("53700d9cd83e146623e6bfb4"), "resource_id" : 7660708, "単語" : "Foo" ...}

次のように保存されます。

{ "_id" : ObjectId("53700d9cd83e146623e6bfb4"), "id" : "", "resourceid" : 7660708, "word" : "Foo"...}

どうすればこれを修正できますか?

4

3 に答える 3

15

エントリを次のように変更します。

type Entry struct {
    Id          string `json:"id" bson:"_id,omitempty"`
    ResourceId  int    `json:"resource_id" bson:"resource_id"`
    Word        string `json:"word" bson:"word"`
    Meaning     string `json:"meaning" bson:"meaning"`
    Example     string `json:"example" bson:"example"`
}

構造タグの構文では、タグ間にコンマを使用しません。これで直ると思います。

于 2014-05-12T02:40:46.153 に答える
8
type Entry struct {
    Id          bson.ObjectId `bson:"_id,omitempty" json:"id"`
    ResourceId  int           `json:"resource_id" bson:"resource_id"`
    Word        string        `json:"word"`
    Meaning     string        `json:"meaning"`
    Example     string        `json:"example"`
}

Count() と Insert() の代わりに、それを行う UpsertId を使用できます。Id が存在する場合、レコードが挿入されていない場合は置き換えられます。

空の ObjectId を持つ Insert() を使用すると、MongoDB で ID の割り当てを処理できます。

編集:カウントクエリを読み違えてください。そこにもエラーがあります。bsonフィールドの名前が「resource_id」であると宣言したため、「resourceid」ではなく「resource_id」にする必要があります

于 2014-05-12T02:49:40.207 に答える