From 96527a67e44c3f86cedba566e3604b4392948eed Mon Sep 17 00:00:00 2001 From: theMackabu Date: Sat, 16 Dec 2023 18:12:08 -0800 Subject: [PATCH] mongo: add more functions --- app.routes | 12 +++++++++--- src/main.rs | 24 ++++++++++++++++++++---- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/app.routes b/app.routes index 260a6bd..5848660 100644 --- a/app.routes +++ b/app.routes @@ -39,11 +39,17 @@ mongo(name) { #[route("/mongo/{name}/{collection}")] mongo(name, collection) { let conn = mongo::connect().db(name).get(collection); - let db = conn.find(); + let list = conn.find().collect(); - print(db.count()); + json(#{count: list.count(), items: list}) +} + +#[route("/one")] +one() { + let conn = mongo::connect().db("app").get("users"); + let list = conn.find_one(#{firstname: "John"}); - json(#{items: ""}) + json(list) } #[route("/example/{id}.txt")] diff --git a/src/main.rs b/src/main.rs index 7aea119..e2efe8a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -296,6 +296,17 @@ mod mongo { } } + #[rhai_fn(global, return_raw, name = "find_one")] + pub fn find_one(collection: Collection, filter: Map) -> Result> { + match collection.find_one(IntoDocument::into(filter), None) { + Ok(cursor) => match cursor { + Some(item) => to_dynamic::(item), + None => to_dynamic::>(vec![]), + }, + Err(err) => Err(format!("{}", &err).into()), + } + } + #[rhai_fn(global, return_raw, name = "find")] pub fn find_filter(collection: Collection, filter: Map) -> Result>, Box> { match collection.find(IntoDocument::into(filter), None) { @@ -312,12 +323,17 @@ mod mongo { } } + #[rhai_fn(global, name = "count")] + pub fn count_collect(items: Vec) -> i64 { items.iter().count() as i64 } + #[rhai_fn(global, return_raw, name = "collect")] pub fn collect(cursor: Arc>) -> Result> { - let cursor = Arc::try_unwrap(cursor).expect("Cursor failure"); - match cursor.collect() { - Ok(items) => to_dynamic::>(items), - Err(err) => to_dynamic::(err.to_string()), + match Arc::into_inner(cursor) { + Some(cursor) => match cursor.collect() { + Ok(items) => to_dynamic::>(items), + Err(err) => to_dynamic::(err.to_string()), + }, + None => to_dynamic::>(vec![]), } } } -- GitLab