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

How to create mongo model and client correctly?

PHPz
Release: 2024-02-09 08:30:10
forward
1165 people have browsed it

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"`
}
Copy after login

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)
Copy after login

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
}
Copy after login

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') }]"
Copy after login

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,
Copy after login

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"`
    ...
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template