Search code examples
mongodbmongodb-.net-driver

MongoDB saving comments to nested array


I'm new to both C# and MongoDB and am having some issues inserting/updating/savings items into a nested array using a repository pattern online ( http://www.primaryobjects.com/cms/article137.aspx ). Here is some code:

Models:

public class BlogModel
{
    [BsonId]
    public ObjectId Id { get; set; }
    public DateTime Date { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Body { get; set; }
    public string Author { get; set; }
    public IList<CommentModel> Comments { get; set; }
}

public class CommentModel
{
    [BsonId]
    public ObjectId Id { get; set; }
    public DateTime Date { get; set; }
    public string Author { get; set; }
    [Required]
    public string Body { get; set; }
}

And the repository pattern:

public void Add<T>(T item) where T : class, new()
{
    _db.GetCollection<T>().Save(item);
}

public void Add<T>(IEnumerable<T> items) where T : class, new()
{
    foreach (T item in items)
    {
        Add(item);
    }
}

How would I add a comment to the nested array using the 'Add' class?


Solution

  • Using this repository pattern, there would be four steps:

    1. Instantiate a repository of type BlogModel
    2. Retrieve the document to which you want to add comments
    3. Add comment(s) to the document
    4. Save the document back to the collection.

    Something like this:

    var myRepository = new Repository<BlogModel>();
    var myDocument = myRepository.Find(some_id);    // retrieve BlogModel document to update
    myDocument.Comments.Add(some_new_comments);    // add to IList
    myRepository.Add(myDocument);     // save changes to the document back to the repository
    

    Note that since your Add repository method uses the C# Driver Save method, it really has the function of insert or update. And in this case you wouldn't have a repository of CommentModel, since that functions as a document array embedded in the BlogModel document.