【问题标题】:MongoDB saving comments to nested arrayMongoDB将注释保存到嵌套数组
【发布时间】:2012-05-13 20:34:37
【问题描述】:

我是 C# 和 MongoDB 的新手,并且在使用在线存储库模式 (http://www.primaryobjects.com/cms/article137.aspx) 将项目插入/更新/保存到嵌套数组中时遇到了一些问题。这是一些代码:

型号:

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; }
}

以及存储库模式:

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);
    }
}

如何使用“添加”类向嵌套数组添加注释?

【问题讨论】:

    标签: mongodb mongodb-.net-driver


    【解决方案1】:

    使用此存储库模式,将有四个步骤:

    1. 实例化类型为 BlogModel 的存储库
    2. 检索要添加 cmets 的文档
    3. 向文档添加评论
    4. 将文档保存回集合中。

    类似这样的:

    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
    

    注意,由于你的Add 存储库方法使用了C# Driver Save 方法,它确实具有insert or update 的功能。在这种情况下,您将没有 CommentModel 的存储库,因为它作为嵌入在 BlogModel 文档中的文档数组起作用。

    【讨论】:

    • 感谢 dbaseman。您认为将更新类添加到我的存储库会更好吗?允许我做类似...public void AddComment(ObjectId postId, Comment comment) { _posts.Collection.Update(Query.EQ("_id", Id), Update.PushWrapped("Comments", comment)); }
    • @user1392537 是的,我想这是有道理的。不过,我不确定如何在不“破坏”通用存储库模式的情况下做到这一点。我猜只是子类 Repository 或使用扩展方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2013-05-18
    • 2012-11-03
    • 2021-08-13
    • 2012-08-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多