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.¯\(ツ)/¯