0

I am trying to use UpdateOne of mongo-go-driver library but this method take bson document. I give it a interface parameter (json).

My question is to find best way to parse my json request to bson for updating fields dynamically. Thank you.

func (s Store) Update(id`enter code here` bson.D, d interface{}) (*mongo.UpdateResult, int32, string) {
    upd := bson.D{
        {
            "$inc", bson.D{
                d,
            },
        },
    }
    c, ctx, _ := getCollection(s.conn, s.dbName, s.collectionName)
    res, err := c.UpdateOne(ctx, id, d)
    if err != nil {
        log.Fatal(err)
        return res, 500, "DATABASE ERROR: Cannot update document"
    }
    return res, 200, "none"
}

I am getting this error:

Error: cannot use d (type inte`enter code here`rface {}) as type primitive.E in array or slice literal: need type assertion
Martin Evans
  • 45,791
  • 17
  • 81
  • 97

1 Answers1

0

You need to pass a bson.D as third parameter of UpdateOne, at least according to this tutorial.

So in your code you shouldn't pass d, but upd to the UpdateOne function:

func (s Store) Update(id`enter code here` bson.D, d interface{}) (*mongo.UpdateResult, int32, string) {
    upd := bson.D{
        {
            "$inc", bson.D{
                d,
            },
        },
    }
    c, ctx, _ := getCollection(s.conn, s.dbName, s.collectionName)
    res, err := c.UpdateOne(ctx, id, upd)
    if err != nil {
        log.Fatal(err)
        return res, 500, "DATABASE ERROR: Cannot update document"
    }
    return res, 200, "none"
}
xarantolus
  • 1,961
  • 1
  • 11
  • 19