Search code examples
rustserdesurrealdb

Failed to create record in SurrealDb


I'm trying to build a simple CRUD Api using SurrealDB as my datastore, but I ran into a strange problem when trying to add a new record. I tried to send the following JSON to the API:

{
    "zipcode":"00-001",
    "city":"Warsaw",
    "country":"Poland",
    "street":"Some street"
}

I got the following as a response:

Failed to convert `{ city: 'Warsaw', country: 'Poland', id: address:936jcs9jtx23qejgn5uc, street: 'Some street', zipcode: '00-001' }` to `T`: invalid type: map, expected a string

I suspect that the problem comes from serde, but I have no idea why it occurs, especially since the current code is practically copied from the documentation.

Here is my model and create function:

#[derive(Serialize, Deserialize, Debug)]
pub struct Address {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub zipcode: String,
    pub city: String,
    pub country: String,
    pub street: String,
}

impl Address {
    pub fn new(zipcode: String, city:String, country:String, street: String) -> Address{
        Address{ id: None, zipcode, city, country, street, }
    }
}
pub type SurrealClient = Surreal<Client>;

pub async fn create(
    client: Arc<SurrealClient>,
    zipcode: String, city: String, country: String, street: String,
) -> Result<Address, SurrealError> {
     let address: Address = Address::new(zipcode, city, country, street);

    match client.create("address").content(address).await{
        Ok(address) => Ok(address),
        Err(e) => Err(e),
    }
}

Solution

  • I believe based on the documentation that id should be parsed as a Thing.

    use surrealdb::sql::Thing;
    
    #[derive(Serialize, Deserialize, Debug)]
    pub struct Address {
        #[serde(skip_serializing_if = "Option::is_none")]
        pub id: Option<Thing>,
        ....