Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added MongoDB example #2535

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

tr1sm0s1n
Copy link

Hello! ^^

Motivation

Recently, I've been trying to create an API service in Rust to communicate with MongoDB using axum. Adding an example would be nice for future developers.

Solution

// defining Member type
#[derive(Debug, Deserialize, Serialize)]
struct Member {
_id: u32,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the _?

Suggested change
_id: u32,
id: u32,

Copy link
Contributor

@Ptrskay3 Ptrskay3 Feb 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this is because MongoDB uses the _id field as primary key.
Maybe it could be #[serde(rename = "_id")] id: u32 to adhere to Rust's convention?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3cd9ded.

Json(input): Json<Member>,
) -> impl IntoResponse {
let result = db.insert_one(input, None).await.unwrap();
println!("{:?}", result);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure we need all this print. Same goes for the ones below.

Suggested change
println!("{:?}", result);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3cd9ded.

async fn create_member(
State(db): State<Collection<Member>>,
Json(input): Json<Member>,
) -> impl IntoResponse {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We generally don't recommend returning impl IntoResponse, see https://docs.rs/axum/latest/axum/response/index.html#regarding-impl-intoresponse.

So I think instead we should write the full type.

Would also be good to not unwrap inside the handler and instead return a Result.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3cd9ded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants