ostafen / clover

A lightweight document-oriented NoSQL database written in pure Golang.
MIT License
677 stars 54 forks source link

Example Request: Unmarshal/Update/Replace #104

Closed idcmp closed 1 year ago

idcmp commented 1 year ago

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?
ostafen commented 1 year ago

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 1 year ago

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.

ostafen commented 1 year ago

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 1 year ago

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

ostafen commented 1 year ago

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 1 year ago

Confirmed this works. Thanks @ostafen !