Search code examples
databasemongodbrusttraitsborrow-checker

How can I insert a doc!{...} into a typed MongoDB collection?


I have a rocket web server and I want to add an auth-token to my sync-MongoDB database. However when I try to insert_one I get an error that the borrow trait of Token is not implemented for the Document type.

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Token {
    username: String,
    token: String,
    timestamp: i64
}
fn set_token(&self, username: &String, token: &String) -> Result<InsertOneResult, mongodb::error::Error> {
    let result = self.tokencol.insert_one(doc! {username: username, token:token, timestamp: 0}, None);
    return result;
}

Here is the relevant snippet of my code. The type of self.tokencol is Collection<Token>.

I tried implementing the Borrow trait myself but did not have any success with that.


Solution

  • If you use Collection<Token> as your collection type, you cannot use doc!{} with .insert_one() since the collection is expecting a Token and not a generic Document (even if it looks like a token). You can either:

    • Just make a Token:

      self.tokencol.insert_one(
          Token {
              username: username.to_owned(),
              token: token.to_owned(),
              timestamp: 0,
          },
          None,
      )
      
    • Convert your collection into an untyped version using .clone_with_type() to Document:

      self.tokencol.clone_with_type::<Document>().insert_one(
          doc! {
              username: username,
              token: token,
              timestamp: 0,
          },
          None,
      )