jjzjj

mongodb - go.mongodb.org/mongo-driver - InsertOne with NilValueObjectId

coder 2024-07-06 原文

我有以下结构

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 字段上的重复 key 错误,无法插入之后的任何帐户。我知道 mongoDB 会自动生成一个 _id 字段,如果有 id,就会使用提供的字段。在我的例子中,在这个创建函数中,a.ID (_id) 始终是 NilValue "_id": ObjectId("000000000000000000000000")

即使我提供的 ID 字段值为 nil,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
}

如果我做错了以及如何做得更好,我将不胜感激。

谢谢!

最佳答案

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

应该是

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

关于mongodb - go.mongodb.org/mongo-driver - InsertOne with NilValueObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56503108/

有关mongodb - go.mongodb.org/mongo-driver - InsertOne with NilValueObjectId的更多相关文章

随机推荐