【问题标题】:go.mongodb.org/mongo-driver - InsertOne with NilValueObjectIdgo.mongodb.org/mongo-driver - 带有 NilValueObjectId 的 InsertOne
【发布时间】:2019-06-08 15:41:19
【问题描述】:

我有以下结构

type Account struct {
    ID       primitive.ObjectID `json:"id" bson:"_id"`
    Email    string             `json:"email"`
    Password string             `json:"password"`
}

还有下面的函数

func (a *Account) Create() map[string]interface{} {

    if resp, ok := a.Validate(); !ok {
        return resp
    }

    hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(a.Password), bcrypt.DefaultCost)
    a.Password = string(hashedPassword)

    users := db.Collection("users")

    insertResult, err := users.InsertOne(context.TODO(), a)

    if err != nil {
        return utils.Message(false, "Error inserting user document "+err.Error())
    }

      ... more code down hre
}

我遇到的问题是我可以插入第一个帐户,但是由于 _id 字段上的 dup 键错误,之后的任何帐户都无法插入。我知道 mongoDB 会自动生成一个 _id 字段,如果有 id 将使用提供的字段。在我的这个创建函数中,a.ID (_id) 始终是 NilValue "_id" : ObjectId("000000000000000000000000")

即使我提供带有 nil 值的 ID 字段,mongoDB 是否可以为我生成 _id?

我需要那里的Account.ID `bson: "_id"` 属性,这样我可以在从 mongoDB 读取时对其进行解码,例如

func GetUser(email string) *Account {
        account := &Account{}
    users := db.Collection("users")

    filter := bson.D{{"email", email}}

    if err := users.FindOne(context.TODO(), filter).Decode(&account); err != nil {
        return utils.Message(false, "Error Retrieving account for "+email)
    }

        // account.ID will be available due to the bson tag
}

如果我做错了,我会很感激一些反馈,以及如何做得更好。

谢谢!

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    我发现了问题。我没有在 bson 标签中添加 ```omitempty`。

    应该是

    type Account struct {
        ID       primitive.ObjectID `json:"id" bson:"_id,omitempty"`
        Email    string             `json:"email"`
        Password string             `json:"password"`
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2021-02-16
      • 1970-01-01
      • 2019-11-22
      • 2016-07-04
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2021-04-18
      相关资源
      最近更新 更多