I tried to save a dynamic object associated with the ProcessID, the dynamic object is completely “dynamic”, sometimes it can be one property with some arbitrary data and name, sometimes it can be 100 properties with absolutely arbitrary names for each property. In fact, this is an object coming from an Angular 5 application that generates the dynamic form (surprise) of some JSON object. My “base” class, the one inserted into mongo, looks like this:
public class MongoSave { [BsonId(IdGenerator = typeof(StringObjectIdGenerator))] public string Id { get; set; } public int ProcessID { get; set; } public BsonDocument DynamicData { get; set; } }
From my first attempt, the DynamicData property was of type object , the controller method got everything in order, assigned the incoming object to the class, but when saving the object in mongo, the values for DynamicData were lost. I only got property names. Tried to use BsonSerialize annotation in my class, but without success.
Having studied a little, I found that BsonDocument has a Parse method, similar to javascript, which parses a string containing a description of an object, so ... I placed such an object with my controller:
{ "ProcessID": 987, "DynamicData": { "name": "Daniel", "lastName": "Díaz", "employeeID": 654 } {
A few things here, I am sending through JS Insomnia (Postman alternative) this JSON for the API. In the real world, I will send this object via Angular, so I have to apply JSON.stringify(obj) to make sure that the JSON object is ok (I don’t know if the Angular HttpClient objects as compressed JSON or as JS objects (I will check this). The action of my controller has been DynamicData to use the Parse method and the DynamicData C # generic object for a string like this:
[HttpPost("~/api/mongotest/save")] public async Task<IActionResult> PostObjectToMongo (MongoSaveDTO document) { MongoSave mongoItem = new MongoSave() { ProcessID = document.ProcessID, DynamicData = BsonDocument.Parse(document.DynamicData.ToString()) }; await _mongoRepo.AddMongoSave(mongoItem); return Ok(); }
MongoSaveDTO is the same as MongoSave without the MongoSave property, and instead of BsonDocument I use the C # generic object , and it saves everything as a charm.