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)

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 infer string[string], but as soon as the value types differ this will break down. A possible solution that avoids the separate update calls is to use Bson as the common type:

    "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); - The tutor 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"]) {