ostafen/clover

Unclear documentation for updating document by ID

l0ngest opened this issue · 2 comments

Hello there, thanks for this awesome project!

I just started using clover and I've run into an issue with updating documents by ID.

Documentation states:

// update the document with the specified id
db.UpdateById("todos", docId, map[string]interface{}{"completed": true})

However, if I use this code exactly as it is, my IDE displays the following error:
"Cannot use 'updates' (type map[string]interface{}) as the type func(doc *d.Document) *d.Document"

Upon further investigation, this makes sense, as db.UpdateById doesn't appear to work the way it's documented. Instead, the method signature is like:
func (db *DB) UpdateById(collectionName string, docId string, updater func(doc *document.Document) *document.Document) error

Since it seems like it's looking for a document, I try this and it seems to work:

// convert myStruct to document
doc := document.NewDocumentOf(myStruct)

// Update doc by ID... note that I am feeding it the "doc" created above
db.UpdateById("myCollection", "id goes here", func(*document.Document) *document.Document { return doc })

However, this seems to overwrite the entire document rather than updating only the fields provided. If the "doc" variable I provide only contains 1 or 2 fields, the database wipes all the other fields and only keeps the new ones I provide.

Could you update the documentation and/or provide some feedback here about how this is supposed to be used?

Thanks in advance! I really appreciate you taking the time.

Hi, @l0ngest,

However, this seems to overwrite the entire document rather than updating only the fields provided. If the "doc" variable I provide only contains 1 or 2 fields, the database wipes all the other fields and only keeps the new ones I provide.

That's exactly how it works, the returned document is replaced with the old one. If you only want to modify one or two fields you can do that using the document which is provided as a parameter to the function, and return it.

db.UpdateById("myCollection", "id goes here", func(doc *document.Document) *document.Document {
 // add or delete fields from doc
 return doc
})

After some tinkering I figured it out. Thank you very much for your help :)