-1

So, I am making an API with actix and MongoDB, and I did some testing with the Rust MongoDB API beforehand, in which the basic code goes like this:

// Collections, basically just db names
let users = client.database("userAccounts").collection("users");
let items = client.database("userAccounts").collection("items");

let item: Document = items.find_one(doc!{"type": 0}, None).await?.unwrap();
let mut user: Document = users.find_one(doc!{"username": "Fyre"}, None).await?.unwrap();

let item_id = item.get("_id").unwrap();
let user_id_arr = user.get_array_mut("itemIds")?;

user_id_arr.append(&mut vec![item_id.clone()]);

This works as expected, but when I put very similar code into an Actix service, it doesn't do anything.

pub async fn add_item_to_user_id(path: web::Path<(String, String)>, app_state: web::Data<AppState>) -> impl Responder
{
    let (item_id, user_id) = path.into_inner(); // Same Collections as the Above Code
    if let Ok(id) = mongodb::bson::oid::ObjectId::from_str(&user_id)
    {
        match app_state.users.find_one(doc!("_id": id), None).await
        {
            Ok(opt) => {
                if let Some(mut doc) = opt
                {
                    if let Ok(ids) = doc.get_array_mut("itemIds")
                    {
                        ids.append(&mut vec![bson::Bson::String(item_id)]);
                        HttpResponse::Ok().body("Item Added!")
                    }
                    else
                    {
                        HttpResponse::InternalServerError().body("Failed to add item?")
                    }
                }
                else
                {
                    HttpResponse::InternalServerError().body("Error Adding Item!")
                }
            },
            Err(err) => HttpResponse::BadRequest().body(format!["Invalid ID!: {}", err])
        }
    }
    else
    {
        HttpResponse::BadRequest().body("Invalid ID!")
    }
}

In the database, the users are reperesented as:

{
    _id: ObjectId("64bef1dc19f7e4334f241ae8"),
    username: 'Fyre',
    email: '[REDACTED]',
    itemIds: []
}

But after the modifications, it should look like:

{
    _id: ObjectId("64bef1dc19f7e4334f241ae8"),
    username: 'Fyre',
    email: '[REDACTED]',
    itemIds: [ '64bef1dc19f7e4334f241ae9' /* Mongo ID of random item in DB */ ]
}

I have also tried to get the array, change in the rust code, and replace using the update() command, and that did work, but I'm wondering why the other method didn't.¯\(ツ)

FyreWolf
  • 11
  • 1
  • 3
  • You definitely need an `update()` call at some point for your data to be persisted to the database. Modifying the struct only in your Rust code won't achieve that. Show us your efforts using that instead. – kmdreko Jul 26 '23 at 00:08
  • kmdreko, I did get the `update()` method working for me, but I'm wondering why the direct change method works in the other code example – FyreWolf Jul 26 '23 at 00:15
  • That first code block should not affect the database; you are either mistaken or not showing the whole picture. – kmdreko Jul 26 '23 at 03:17

0 Answers0