Kamva / mgm

Mongo Go Models (mgm) is a fast and simple MongoDB ODM for Go (based on official Mongo Go Driver)
Apache License 2.0
754 stars 63 forks source link

Get Create inserted ID #36

Closed henri9813 closed 3 years ago

henri9813 commented 3 years ago

Hello,

I would like to retrieve the ID of the fresh inserted document.

Taking this snippet from the documentation:

book := NewBook("Pride and Prejudice", 345)

// Make sure to pass the model by reference.
err := mgm.Coll(book).Create(book)

I would like to retrieve the "book" ID, how can i do this without perform another search ?

Best regards

mehran-prs commented 3 years ago

Hi @henri9813 mgm sets your model's id when you save it, you just need to pass your model by reference.

book:=&Book{Name:"blah blah"}
err := mgm.Coll(book).Create(book)
fmt.Println(book.ID)

or

book:=Book{Name:"blah blah"}
err := mgm.Coll(book).Create(&book)
fmt.Println(book.ID)
henri9813 commented 3 years ago

Hello,

Oh that's perfect !!

That's exactly what i want !

Thank you, maybe could you add this into the documentation ?

Best regards

mehran-prs commented 3 years ago

You're welcome, it's in documentation :) in comment of first instance creation.

book := NewBook("Pride and Prejudice", 345)

// Make sure to pass the model by reference.
err := mgm.Coll(book).Create(book)
henri9813 commented 3 years ago

Okay, that was not explicit for me but thank you.

// Make sure to pass the model by reference to have it updated after the creation

It's better no ?

mehran-prs commented 3 years ago

Maybe.

seantcanavan commented 2 years ago

This wasn't immediately obvious to me either for what it's worth. A small piece of documentation can't hurt.

mehran-prs commented 2 years ago

@henri9813 Thanks for the better doc. https://github.com/Kamva/mgm/commit/93cb042a4746084f2492df8e7ca7dc6175c814c3