Hello Patrick,
thank you for your response.
Would it be too much to ask for a complete CRUD example with actix-web?
I’m pretty new to Rust and I’m finding it very unintuitive, having a hard time with learning the language, despite this being my 4th programming language I’m getting into.
I’ll post the files I have and the cargo.toml
main.rs
mod model;
mod handler;
use mongodb::Client;
use std::io;
use actix_web::{HttpServer, App, web};
pub struct State {
client: mongodb::Client
}
#[actix_rt::main]
async fn main() -> io::Result<()> {
let client = Client::with_uri_str("mongodb://localhost:27017/").await.expect("mongo error");
HttpServer::new(move || {
App::new()
.data(State{client: client.clone()})
.route("/", web::get().to(handler::index))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
model.rs
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
pub struct Blog {
#[serde(rename = "_id")]
pub id: bson::oid::ObjectId,
pub name: String,
pub description: String,
}
#[derive(Serialize, Deserialize)]
pub struct Post {
#[serde(rename = "_id")]
pub id: bson::oid::ObjectId,
pub slug: String,
pub author: String,
pub title: String,
pub body: String,
}
#[derive(Serialize, Deserialize)]
pub struct Comment {
#[serde(rename = "_id")]
pub id: bson::oid::ObjectId,
pub author: String,
pub body: String,
}
handler.rs
use actix_web::{web, HttpRequest, Responder, HttpResponse};
use crate::State;
use crate::model::Blog;
pub async fn index(_data: web::Data<State>, req: HttpRequest) -> impl Responder {
let coll = _data.client.database("mblog").collection("blogs");
let cursor = coll.find(None, None);
let mut m: Vec<Blog> = Vec::new();
for result in cursor {
if let Ok(item) = result {
m.push(item)
}
}
HttpResponse::Ok().json(m)
}
[package]
name = "mblog"
version = "0.1.0"
authors = [""]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
mongodb = "1.0.0"
actix-web = "2"
actix-rt = "1.1.1"
serde = "1.0.114"
bson = "1.0.0"
The following error occurs
error[E0277]: `impl std::future::Future` is not an iterator
--> src/handler.rs:10:19
|
10 | for result in cursor {
| ^^^^^^ `impl std::future::Future` is not an iterator
|
= help: the trait `std::iter::Iterator` is not implemented for `impl std::future::Future`
= note: required by `std::iter::IntoIterator::into_iter`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: could not compile `mblog`.