我有一个模型想要插入并从 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"`
}
我希望 ID 字段在 mongo 内部自动递增,所以我将 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') }]"