On Thu, 07 Sep 2017 08:51:42 GMT, Sönke Ludwig wrote:
On Tue, 22 Aug 2017 16:18:38 GMT, Rey Valeza wrote:
This has been an issue with me since way back but it is only now that I am mentioning this.
Whenever I save to MongoDB with data in different data types, I get this error:
(...)
source/store.d(118,13): Error: incompatible types for ((tutor.photo) : (tutor.rating)): 'string' and 'float'
dmd failed with exit code 1.Here is my code:
void appendTutor(Tutor tutor) { tutordocs.insert ([ "email":tutor.email, "uname":tutor.uname, "password":tutor.password, "city":tutor.city, "province":tutor.province, "country":tutor.country, "photo":tutor.photo, "rating":tutor.rating ]); }
Here is the data:
struct Tutor { string email; string uname; string password; string city; string province; string country; string[] subjects; string photo; float rating; int raters; }
(...)
The error comes from the fact that
["x": y, ...]
creates a statically typed associative array. In the code with the workaround, it will inferstring[string]
, but as soon as the value types differ this will break down. A possible solution that avoids the separateupdate
calls is to useBson
as the common type:tutordocs.insert([ "email": Bson(tutor.email), "rating": Bson(tutor.rating), "subjects": serializeToBson(tutor.subjects), ... ]);
But as long as the struct matches the database fields, the shortest and most efficient approach is to simply insert the object itself:
tutordocs.insert(tutor);
- Thetutor
object will automatically be serialized to BSON and will be stored exactly the same as in the original version.There is also an optional type argument for
.find
and.findOne
, so that deserialization can also happen implicitly:foreach (Tutor t; tutordocs.find!Tutor(["city": "London"]) { ... }
Thanks so much, Sönke!