Home  >  Article  >  Backend Development  >  How to create mongo model and client correctly?

How to create mongo model and client correctly?

PHPz
PHPzforward
2024-02-09 08:30:101109browse

How to create mongo model and client correctly?

php editor Apple will introduce you how to correctly create mongo models and clients. When developing with MongoDB, creating models and clients is a very important step, as they determine your flexibility and efficiency in subsequent operations. First, you need to enable MongoDB support by installing the MongoDB extension. You can then use the API provided by MongoDB to create models and clients. When creating a model, you need to define relevant information such as collection names, fields, and indexes. When creating a client, you need to specify MongoDB connection information, such as host name, port number, and authentication information. By creating models and clients correctly, you will be able to better operate the MongoDB database and improve development efficiency and code quality.

Question content

I have a model that 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 auto-increment inside mongo, so I leave the ID field empty:

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

Additionally, when creating the 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
}

Can you tell me what I'm doing wrong? I haven't really understood how to properly use the _id field in 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

If not passed in, MongoDB will generate the ID. In your structure, the IDs you pass in are all zeros.

You can do two things:

You can generate it yourself:

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

Or, you didn't pass it in:

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

Then, if the ID is not initialized, the ID will be generated.

The above is the detailed content of How to create mongo model and client correctly?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Inheritance in GoNext article:Inheritance in Go