I'm doing CRUD in MongoDB. I tried this example but I'm its not working. I'm getting access violation error then stream read error. Here is my code:
var
fdCon : TFDConnection;
fdMongQuery : TFDMongoQuery;
mDoc : TMongoDocument;
begin
try
fdCon := TFDConnection.Create(nil);
fdMongQuery := TFDMongoQuery.Create(nil);
try
fdCon.Params.Clear;
fdCon.Params.DriverID := 'Mongo';
fdCon.Params.Add('Server=' + 'localhost');
fdCon.Params.Add('Port=' + '27017');
fdCon.Open;
fdMongQuery.Close;
fdMongQuery.FieldDefs.Clear;
fdMongQuery.FormatOptions.StrsTrim2Len := True;
fdMongQuery.Connection := fdCon;
fdMongQuery.DatabaseName := 'HR';
fdMongQuery.CollectionName := 'employee';
mDoc :=
TMongoDocument.Create(TMongoEnv(fdCon))
.Add('name', 'ago')
.Add('age', 12)
.Add('address', 'PH')
;
fdMongQuery.Collection.Insert(mDoc); // access violation > stream read error
mDoc.Free;
finally
fdMongQuery.Free;
fdCon.Free;
end;
except
end;
end;
Where did I go wrong?
This construction is wrong:
You are type-casting the
TFDConnectionobject toTMongoEnvwhen creating theTMongoDocumentobject, but that is an illegal type-cast (if you had used theasoperator for the cast, it would have raised anEInvalidCastexception at runtime).TMongoDocumentexpects an actualTMongoEnvobject.You need to instead type-cast the
TFDConnection.CliObjproperty toTMongoConnectionafter connecting to a MongoDB server, and then you can use theTMongoConnection.Envproperty to get theTMongoEnvobject. This is even explained in Embarcadero's documentation:FireDAC.Phys.MongoDBWrapper.TMongoEnv
FireDAC.Phys.MongoDBWrapper.TMongoConnection
So, try this instead: