I've a Parent Entity that has a property of list of Child Entities. Initially on Insert I don't have values for the child entities.
But when I try to Update(by calling push) the document with Child Entities it fails.
This works when I insert a dummy child entity value to the Initial Add .
This is because the embedded document refers to null .
public class ParentDocument : Entity
{
public string prop1 { get; set; }
public List<EmbeddedDocument> EmbeddedDocuments { get; set; }
}
public class EmbeddedDocument
{
public string prop2{ get; set; }
}
The parent is saved First
_collection.InsertOne(new ParentDocument(){prop1 ="value"});
and later when I Update the document
var builder = Builders<ParentDocument>.Update;
var updateDefintion = builder.Push(x => x.EmbeddedDocuments ,new EmbeddedDocument() { prop2= "value2" });
_collection.UpdateManyAsync(x=>x.Id==ParentDocumentId, updateDefinition)
error occurs "A write operation resulted in an error mongodb"
But this push works if I have already inserted Embedded Document(s) in the List on first insert.
I think that is because of that the EmbeddedDocuments property is Inserted as null the push doesn't work.
I also tried passing empty List to intial Insert,but not helped.
One Idea would be to check if the count of List of Embedded documents is zero and call
Builder.set(x=>x.EmbeddedDocuments ,new List<EmbeddedDocument>(){ item1 });
But this will cost a query , which I don't want to.
Is there any other solution?
Thanks in Advance
To Hazard a guess, it's because the "array" field in the database is null after the insert. You either need to make the initial value in the database an empty array, or you need to make it not-present. You can either:
This can be reproduced in the shell very easily:
This will error. However, if you remove y from the insertion or change it to an empty array, the update will succeed.