Home > other >  Avoid duplication when serializing/deserializing mongodb documents
Avoid duplication when serializing/deserializing mongodb documents

Time:05-31

I have 2 collections:

  • profiles
  • dances
struct Profile {
   id: String,
   firstname: String,
   dances: Vec<String>
}

struct DanceModel {
   id: String,
   name: String,
}

I have a find query which does a lookup on the dances collection.

let cursor = profile_collection.aggregate(pipeline, None).await.unwrap();
let results = cursor.try_collect().await.unwrap_or_else(|_| vec![]);
let profile = results.first().unwrap();        
let result = bson::from_document::<ProfileResult>(profile.clone());

I created a new model like so:

struct ProfileResult {
   id: String,
   name: String,
   dances: Vec<DanceModel>
}

As you can see, the id and name fields are being duplicated, and I have 2 models for the same data.

Is there any way to avoid duplication of attributes and data models?

CodePudding user response:

It looks like you are trying to apply an object concept to a procedural technology.

To work around this issue, you can create an IdName struct and apply that struct to the model in a uid field.

struct IdName {
   id: String,
   name: String,
}

struct Profile {
   id: String,
   firstname: String,
   dances: Vec<String>
}

struct DanceModel {
   uid: IdName
}

struct ProfileResult {
    uid: IdName
    dances: Vec<DanceModel>
}
  • Related