From 0cb1e28c20e29fe0961649ebd41ee5e7ef20fb9a Mon Sep 17 00:00:00 2001 From: JMARyA Date: Thu, 18 Jul 2024 14:20:59 +0200 Subject: [PATCH] ref validate performance --- src/model/reference.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/model/reference.rs b/src/model/reference.rs index 723f55d..8508b06 100644 --- a/src/model/reference.rs +++ b/src/model/reference.rs @@ -1,3 +1,4 @@ +use mongodb::options::FindOneOptions; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::{col, get_mongo, id_of}; @@ -30,6 +31,23 @@ impl Reference { self.0.starts_with(col) } + /// Check for existence of reference + pub async fn exists(&self) -> Option { + let (col, id) = self.0.split_once("::")?; + let db = get_mongo!(); + let col = col!(db, col); + let res = col + .find_one( + id_of!(id), + FindOneOptions::builder() + .projection(mongodb::bson::doc! { "_id": 1}) + .build(), + ) + .await + .ok()?; + Some(res.is_some()) + } + /// Get the raw `Document` behind the `Reference` from the database. pub async fn get_document(&self) -> Option { let (col, id) = self.0.split_once("::")?; @@ -50,7 +68,7 @@ impl Validate for Reference { //self.0.split_once("::").is_some() // right - self.get_document().await.is_some() + self.exists().await.unwrap_or(false) } }