更新一个Mongo JSON对象

huangapple go评论51阅读模式
英文:

Update a mongo json object

问题

我正在尝试更新一个文档,但它没有更新,也没有抛出任何错误。

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"`
}

我不确定id是否是问题,所以我手动将它输入为一个字符串,但没有效果。

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
}

日志:

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

我尝试过UpdateManyUpdateOneUpdateById

我发送的JSON数据的一小部分:

{
    "id": "649411c5d1c770dd462bd181",
    "title": "Algorithms",
    "description": "An awesome course",
    // 其他字段
}

如果有建议,将不胜感激。

英文:

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.

答案1

得分: 0

我希望我没有漏掉任何东西,但我认为你把ID弄混了 更新一个Mongo JSON对象
尝试将过滤器更改为以下之一:

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

或者

filter := bson.D{
    {"id", c.Id},
}

*更新
刚刚注意到你在使用UpdateByID(),但你传递了一个过滤器,尝试直接传递objID本身或者使用UpdateOne(),像这样:

result, err := r.collection.UpdateByID(ctx, objID, update)

或者

result, err := r.collection.UpdateOne(ctx, filter, update)
英文:

I hope I'm not missing anything, but I think you got the IDs mixed up 更新一个Mongo JSON对象
Try to change the filter to either:

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

or

filter := bson.D{
    {"id", c.Id},
}

*Update
Just recognized you are using UpdateByID() but you pass a filter, try passing objID itself or use UpdateOne() instead like:

    result, err := r.collection.UpdateByID(ctx, objID, update)

or

    result, err := r.collection.UpdateOne(ctx, filter, update)

答案2

得分: -1

以下是翻译好的内容:

我相当确定,如果您将 JSON 传递为

  "_id": "649411c5d1c770dd462bd181"

并且这些数据以某种方式加载到 Course 结构中,那么 c.Id 最终将成为普通字符串,而不是真正的 ObjectId。稍后在您的 error 函数中,您调用

primitive.ObjectIDFromHex(id)

但是 "649411c5d1c770dd462bd181" 不是有效的 Go 十六进制字符串;它需要一个 0x0X 作为前缀(https://www.includehelp.com/golang/hexadecimal-literals.aspx#:~:text=Hexadecimal%20numbers&text=In%20Go%20programming%20language%2C%20a,either%20in%20Uppercase%20or%20Lowercase)。

尝试在前面添加 0x,例如:

    filter := bson.D{
        {"_id", primitive.ObjectIDFromHex('0x' + c.Id)}
    }
英文:

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

huangapple
  • 本文由 发表于 2023年6月22日 17:38:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76530516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定