I need to append a new comment to a array element that is part of a MongoDB document via C# but can't figure out how to do it.
The strange thing is that when I'm inserting a document with tags which are stored in an array of string element, it works as expected:
var post = new Post
{
Title = model.Title,
Author = User.Identity.Name,
CreatedAtUtc = DateTime.Now,
Content = model.Content,
Tags = model.Tags.Split(",".ToCharArray()).ToList()
};
Now when I try to add a new comment to an existing document, I use the following:
var filter = Builders<Post>.Filter.Eq("_id", model.PostId);
var update = Builders<Post>.Update.Push<Comment>("Comments",
new Comment
{
Author = User.Identity.Name,
CreatedAtUtc = DateTime.Now,
Content = model.Content
});
var ret = await blogContext.Posts.FindOneAndUpdateAsync(filter, update);
But this leaves my Comments element empty in my document:
"_id" : ObjectId("5b82ec466b63730fe4c51915"),
"Author" : "Joe",
"Content" : "content1",
"CreatedAtUtc" : ISODate("2018-08-26T18:06:53.238Z"),
"Title" : "title1",
"Comments" : [ ],
"Tags" : [
"tag1.1",
"tag1.2",
" tag2.2"
]
Can anyone clarify how do I append an additional comment to an existing document?
Thanks
UPDATE-1:
I've found this question on StackOverflow: How to use $push update modifier in MongoDB and C#, when updating an array in a document which described my exact problem, except that the array used in an array of string rather than an array of object/document but I still thought it would resolved it by adapting my code to match it:
var filter = Builders<Post>.Filter.Eq("_id", model.PostId);
var update = Builders<Post>.Update
.Push<Comment>(e => e.Comments, new Comment
{
Author = User.Identity.Name,
CreatedAtUtc = DateTime.Now,
Content = model.Content
});
await blogContext.Posts.FindOneAndUpdateAsync(filter, update);
but this is still leaving my Comments array element empty just as posted in the original question.
Any ideas?