thedodd / wither

An ODM for MongoDB built on the official MongoDB Rust driver.
https://docs.rs/wither
Other
324 stars 40 forks source link

prefer index name over automatic generation by keys #82

Closed 27justin closed 9 months ago

27justin commented 3 years ago

Defining a struct with a text index causes the application to crash.

#[model(index(keys=r#"doc!{"title": "text"}"#))]
pub struct Book {
    #[serde(rename="_id", skip_serializing_if="Option::is_none")]
    id: Option<ObjectId>,
    title: String
}

During the first run with the new index everything works fine, the index is created and no error occurs. On every subsequent start however, the application crashes with the following error: Mongo(Error { kind: CommandError(CommandError { code: 27, code_name: "IndexNotFound", message: "index not found with name [_fts_0__ftsx_1]", labels: [] }), labels: [] })

This happens because MongoDB creates the text index over the keys _fts and _ftsx. During the synchronization step of wither, the index is now "unknown" and wither tries to drop it, resulting in the above error since the index isn't named _fts_0__ftsx_1 but instead is actually called title_0. As of right now, the only way to avoid this crash is to remove the Model::sync call of the struct.

This pull request makes wither prefer IndexModel.options.name over the generate_index_name_from_keys function. If however, for some reason, IndexModel.options.name isn't set it defaults back to the generate_index_name_from_keys function.

simoneromano96 commented 2 years ago

I think this should be blocked, in the new driver they added again the IndexModel, we should try to adjust the indexes using that.