I am trying to write a general purpose Web Api controller that will allow me to save a JSON document to a collection WITHOUT specifying a C# type. I\'ve tried to condense the co
I was trying to save some dynamic object associated to a ProcessID, the dynamic object it's totally "dynamic", sometimes it can be one property with some arbitrary data and name, sometimes it can be a 100 properties with totally arbitrary names for each property. In fact, it's an object coming from an Angular 5 app that generates a dynamic form from (surprise) some JSON object. My "base" class, the one that get inserted into mongo it's like this:
public class MongoSave {
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string Id { get; set; }
public int ProcessID { get; set; }
public BsonDocument DynamicData { get; set; }
}
On my first attempt the DynamicData
property was type object
, the controller method received everything ok, assign the incoming object to the class but when saving the object to mongo the values for DynamicData
were lost. I was getting only the property names. Tried to use the BsonSerialize
annotation in my class but with no success.
Researching a little bit i discovered that BsonDocument
has a Parse
method similar to javascript that parse a string containing an object description, so... i posted an object like this to my controller:
{
"ProcessID": 987,
"DynamicData": {
"name": "Daniel",
"lastName": "Díaz",
"employeeID": 654
}
{
A few things here, i'm sending via Insomnia (a Postman alternative) this JSON to the API. In real world i'll be sending this object via Angular so i have to be sure to apply JSON.stringify(obj)
to be sure that the JSON object it's ok (don't know for sure if the Angular HttpClient
post objects as stringified JSON or as JS objects (i'll test that). Changed my controller action to use the Parse
method and the DynamicData
C# generic object
to string like this:
[HttpPost("~/api/mongotest/save")]
public async Task PostObjectToMongo (MongoSaveDTO document) {
MongoSave mongoItem = new MongoSave() {
ProcessID = document.ProcessID,
DynamicData = BsonDocument.Parse(document.DynamicData.ToString())
};
await _mongoRepo.AddMongoSave(mongoItem);
return Ok();
}
The MongoSaveDTO
it's the same as MongoSave
without the BsonId
property and instead of BsonDocument
i'm using C# generic object
type and everything saves like a charm.