ostafen/clover

Example Request: Unmarshal/Update/Replace

idcmp opened this issue · 6 comments

idcmp commented

I can't seem to figure out how to do this. I have a struct whose fields are tagged for clover. I would like to read in a document, Unmarshal it to my struct, make changes to my struct, then update the existing document using my struct.

import c "github.com/ostafen/clover/v2"

type Example struct {
  Foo string `clover:"foo"`
}

doc, .. := c.Query(Find...))

var example Example
doc.Unmarshal(&example)
example.Foo = example.Foo + " bar "

c.ReplaceById( .... ) // can't use NewDocumentOf() since objectId isn't set?

HI, @idcmp, why can't you use the ReplaceById() or the other methods?

If you have to modify an existing document, which you fetched through a query, then you have the document id, so you can use
ReplaceById()

idcmp commented

I could, but ReplaceById checks that the *Document passed in has the same objectId has the 2nd arg. Since the *Document is created by NewDocumentOf(example), that Document doesn't have a objectId, so the update fails.

You can simply set the document id on the new document so that it matches the one of the second argument, can't you?

idcmp commented

I'll give that a try, I wasn't sure if that was the right way since the objectId constant is package private.

Yes, but it's Simply a constant for avoiding to directly use the "_id" literal.
You can change any field in the document, though

idcmp commented

Confirmed this works. Thanks @ostafen !