我有一个模型想要从MongoDB中插入和读取:

type TripFeedback struct {
    ID        primitive.ObjectID `json:"_id" bson:"_id"`
    UserID    string             `json:"user_id" bson:"user_id"`
    WaybillID uint64             `json:"waybill_id" bson:"waybill_id"`
    Rating    Rating             `json:"rating" bson:"rating"`
    Comment   string             `json:"comment" bson:"comment"`
    CreatedAt time.Time          `json:"created_at" bson:"created_at"`
}

我希望Mongo中的ID字段自动递增,因此我将ID字段保留为空:

    feedback := model.NewTripFeedback(
        createRequest.UserID,
        createRequest.WaybillID,
        rating,
        createRequest.Comment,
        createRequest.ReceivedAt,
    )
    _, err = r.collection.Create(ctx, feedback)

在创建存储库时,我也是这样做的:


// NewFeedbackRepository connects to mongo db and feedback collection.
func NewFeedbackRepository(ctx context.Context, client *mongo.Client) (*FeedbacksRepository, error) {
    r := FeedbacksRepository{
        c:       client.Database(dbName).Collection(feedbackCollectionName),
        metrics: NewMetrics(),
    }
    if err := r.migrate(ctx); err != nil {
        return nil, err
    }
    return &r, nil
}

// migrate ensures presence of dossier collection in database.
func (r *FeedbacksRepository) migrate(ctx context.Context) error {
    mdb := r.c.Database()
    cs, lcErr := mdb.ListCollectionNames(ctx, bson.M{"name": feedbackCollectionName})
    if lcErr != nil {
        return fmt.Errorf("migrate: list collections error: %w", lcErr)
    }
    if len(cs) == 0 {
        if err := mdb.CreateCollection(ctx, feedbackCollectionName); err != nil {
            return fmt.Errorf("migrate: create collection error: %w", err)
        }
    }
    return nil
}

你能告诉我我做错了什么吗?我真的不知道如何正确使用mongo db中的_id字段.我希望它在Mongo内部创建和处理

write errors
: [E11000 duplicate key error collection: drive.feedback index: _id_ dup key: { _id: ObjectId('000000000000000000000000') }]"

推荐答案

如果没有传入,MongoDB会生成ID.在您的 struct 中,您传入的ID全为零.

您可以做两件事:

您可以自己生成它:

 feedback := model.NewTripFeedback(
        ID: primitive.NewObjectID(),
        createRequest.UserID,

或者,您不将其传入:

type TripFeedback struct {
    ID        *primitive.ObjectID `json:"_id" bson:"_id,omitempty"`
    UserID    string             `json:"user_id" bson:"user_id"`
    ...

然后,如果您不初始化ID,它将被生成.

Database相关问答推荐

如何在没有sqlmock的情况下模拟db ping

如何在mongodb数据库中设置导入的CSV文件的字段之间的关系

[mongodb],如何通过聚合获得具有许多不同字段的文档的最大值?子字段名称相同

如何将 Scylla DB 中的计数器列重置为零?

SQLServer:如何对按外键依赖性排序的表名进行排序

在 MySQL 中创建表时如何定义列的默认值?

如何将 MySQL 5.5.40 升级到 MySQL 5.7

Zend 框架 - 为什么我应该使用数据映射器/Db_Table_Row?

NoSql DB 和 OO Db 有什么区别?

如何从 SQLite 数据库中读取数据?

文件访问速度与数据库访问速度

行之间的 SQL 差异

是否有一个 postgres 命令来列出/删除所有materialized视图?

你可以在一个 Hibernate Session 中有多个事务吗?

Sqlite 和 Python - 使用 fetchone() 返回字典?

QSqlDatabase & QSqlQuery 的正确方法是什么?

如何使用反射调用扫描可变参数函数

Spring data : CrudRepository 的保存方法和更新

Windows phone 7 的本地 Sql 数据库支持

如何知道mongodb使用的是哪个存储引擎?