From a8e72efea0280bacbe35ac4cec4d05102a9ce850 Mon Sep 17 00:00:00 2001 From: JMARyA Date: Fri, 3 May 2024 18:45:23 +0200 Subject: [PATCH] fix reinit --- src/db.rs | 7 +++++++ src/item.rs | 31 ++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/db.rs b/src/db.rs index ba94835..7d4f6e8 100644 --- a/src/db.rs +++ b/src/db.rs @@ -30,6 +30,13 @@ macro_rules! get_mongo { }; } +#[macro_export] +macro_rules! id_of { + ($id:expr) => { + doc! { "_id": $id} + }; +} + pub struct ItemDB { index: mdq::Index, mongodb: mongodb::Client, diff --git a/src/item.rs b/src/item.rs index 31015c8..64e0159 100644 --- a/src/item.rs +++ b/src/item.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use crate::collect_results; +use crate::{collect_results, id_of}; use futures::TryStreamExt; use mongodb::{bson::doc, ClientSession, Collection}; @@ -60,17 +60,26 @@ impl ItemEntry { log::info!("Adding item {} to DB", self.name); let items: Collection = mongodb.database("cdb").collection("items"); - items - .insert_one( - mongodb::bson::doc! { - "_id": self.name.clone(), - "name": self.name.clone(), - "category": self.category.clone() - }, - None, - ) + + let doc = mongodb::bson::doc! { + "_id": self.name.clone(), + "name": self.name.clone(), + "category": self.category.clone() + }; + + if items + .find_one(id_of!(&self.name), None) .await - .unwrap(); + .unwrap() + .is_none() + { + items.insert_one(doc, None).await.unwrap(); + } else { + items + .find_one_and_update(id_of!(&self.name), doc, None) + .await + .unwrap(); + } } }