Search code examples
rustbson

InvalidMapKeyType when encoding a HashMap to bson


I want to encode a HashMap<u64, usize> using bson::to_bson() in order to store it in MongoDB.

When I ran the code, it panicked and told me that InvalidMapKeyType(FloatingPoint(....)). Can't I use this method to encode HashMap in such a type?


Solution

  • The BSON library disallows all keys that are not strings. The BSON spec states that a document is a sequence of elements, each element must be preceded by a name, and a name can only be a string.

    Changing your HashMap to use a string as the key should solve the problem.


    Your question doesn't make any sense to me. You state that you have a HashMap<u64, usize> but your error snippet states that it's because of a FloatingPoint!

    This is why you should always create an MCVE and then provide it when asking a question. I created this sample which does exactly as you stated and I get a different error:

    extern crate bson; // 0.8.0
    
    use std::collections::HashMap;
    
    fn main() {
        let mut thing = HashMap::new();
        thing.insert(0_u64, 1_usize);
    
        match bson::to_bson(&thing) {
            Ok(e) => println!("{:?}", e),
            Err(e) => println!("Got an error: {:?}, {}", e, e),
        }
    }
    
    Got an error: UnsupportedUnsignedType, BSON does not support unsigned type
    

    If I change the HashMap to signed numbers, then I get the same class of error:

    thing.insert(0_i64, 1_isize);
    
    Got an error: InvalidMapKeyType(I64(0)), Invalid map key type: I64(0)
    

    You can't even make a HashMap using a f64 as the key in Rust because it doesn't implement Hash or Eq, so I have no idea how you got that specific error.