skip to Main Content

I am trying to update a document but it doesn’t update and it doesn’t throw any errors.

type Course struct {
    ObjectId    primitive.ObjectID `bson:"_id, omitempty"`
    Id          string             `json:"id"`
    Title       string             `json:"title"`
    Description string             `json:"description"`
    Lessons     string             `json:"lessons"`
    Duration    string             `json:"duration"`
    Details     struct {
        Title             string `json:"title"`
        Instructor        string `json:"instructor"`
        Introduction      string `json:"introduction"`
        Topics            string `json:"topics"`
    } `json:"course_details"`
}

I was not sure if the id was the issue, so I manually entered it as a string, which had no effect.

func (r *CourseRepo) UpdateCourse(ctx context.Context, c *Course) error {
    clog := log.GetLoggerFromContext(ctx)

    objID, err := primitive.ObjectIDFromHex(c.Id)
    if err != nil {
       return err
    }

   filter := bson.D{
     {"_id", objID},
   }

    update := bson.D{
        {"$set", bson.D{
            {"title", c.Title},
            {"description", c.Description},
            {"lessons", c.Lessons},
            {"duration", c.Duration},
            {"course_details", c.Details},
        },
        },
    }

    clog.InfoCtx("Filter: %+v", log.Ctx{"filter ": filter})
    clog.InfoCtx("Update: %+v", log.Ctx{"update ": update})

    result, err := r.collection.UpdateByID(ctx, filter, update)
    if err != nil {
        clog.Error(err)

        return err
    }

    clog.InfoCtx("Update Result", log.Ctx{"result ": result})

    return nil
}

logs:

"msg":"Update Result","result ":{"MatchedCount":0,"ModifiedCount":0,"UpsertedCount":0,"UpsertedID":null}}

I have tried UpdateMany / UpdateOne and / UpdateById.

Small snip it of the json I am sending…

   {
        "id": "649411c5d1c770dd462bd181",
        "title": "Algorithms",
        "description": "An awesome course",

Any advice will be greatly appreciated.

3

Answers


  1. Based on the code you provided, there are a few potential issues that could prevent the document from being updated:

    Make sure you have a valid MongoDB connection and that the collection field in your CourseRepo struct is properly initialized.

    Ensure that the c.Id field contains a valid primitive.ObjectID value. You mentioned that you tried entering it as a string, but it should be an ObjectID type. You can create a new ObjectID by using primitive.NewObjectID() if needed.

    Verify that the filter and update variables are constructed correctly. You can add some logging statements to print their values and see if they match your expectations.

    Check if the document with the given _id exists in the collection. If the document doesn’t exist, the update operation won’t throw an error but will also not update any documents.

    Ensure that the user executing the update operation has the necessary permissions to update documents in the collection.

    Here’s an updated version of your code with some logging statements for troubleshooting:

    func (r *CourseRepo) UpdateCourse(ctx context.Context, c *Course) error {
        clog := log.GetLoggerFromContext(ctx)
    
        filter := bson.D{
            {"_id", c.Id},
        }
    
        update := bson.D{
            {"$set", bson.D{
                {"title", c.Title},
                {"description", c.Description},
                {"lessons", c.Lessons},
                {"duration", c.Duration},
                {"course_details", c.Details},
            }},
        }
    
        clog.Infof("Filter: %+v", filter)
        clog.Infof("Update: %+v", update)
    
        result, err := r.collection.UpdateByID(ctx, filter, update)
        if err != nil {
            clog.Error(err)
            return err
        }
    
        clog.Infof("Update Result: %+v", result)
    
        return nil
    }
    

    By adding the logging statements, you can inspect the values of the filter and update variables and check the result of the update operation. This should help you identify any potential issues with the update process.

    Login or Signup to reply.
  2. I am fairly sure if you are passing JSON as

      "_id": "649411c5d1c770dd462bd181"
    

    and this is somehow loaded into the Course struct, then c.Id is ending up a regular string, not a real ObjectId. Later, in your error function, you call

    primitive.ObjectIDFromHex(id)
    

    but "649411c5d1c770dd462bd181" is not a valid Go hex string; it needs a 0x or 0X as a prefix (https://www.includehelp.com/golang/hexadecimal-literals.aspx#:~:text=Hexadecimal%20numbers&text=In%20Go%20programming%20language%2C%20a,either%20in%20Uppercase%20or%20Lowercase).

    Try prepending 0x e.g.:

        filter := bson.D{
            {"_id", primitive.ObjectIDFromHex('0x' + c.Id)}
        }
    
    
    Login or Signup to reply.
  3. I hope I’m not missing anything, but I think you got the IDs mixed up 🙂
    Try to change the filter to either:

    filter := bson.D{
        {"_id", c.ObjectId},
    }
    

    or

    filter := bson.D{
        {"id", c.Id},
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search