How to properly create mongo model and client?

Advertisements

I have a model i want to insert and read from 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"`
}

I want the ID field to be automatically incremented inside mongo, so i keep ID field empty:

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

Also with creating repository i do this:


// 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
}

Could you please tell me what do i do wrong? I haven’t really understood how to properly work with _id field inside mongo db. I want it to be created and handled inside mongo

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

>Solution :

MongoDB will generate the ID if it is not passed in. In your structure, you are passing in an ID which is all zeros.

There are two things you can do:

You can generate it yourself:

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

Or, you do not pass it in:

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

Then, if you do not initialize ID, it will be generated.

Leave a ReplyCancel reply