search

Home  >  Q&A  >  body text

mongodb - 评论放在list里,怎么为每条评论创建唯一标识符id?

MongoDB里,我将评论以dict形式存放在list里,由于要考虑到评论的修改和删除,所以不知道怎样给这些评论创建id,各位有没有好办法?

{
        "_id" : ObjectId(),
        "comments" : [
                {
                        "id" : '#就是这里的id#',
                        "text" : "",
                },
        ]
}
天蓬老师天蓬老师2800 days ago775

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-21 11:19:54

    Can you use MongoDB’s ObjectId

    UPDATE:

    Comments should be attached to the article, not subordinate to the article

    So, create another collection, put comments, and then it contains an indexed field pointing to the objid of the article.

    @felix021: Well, add a field for the current maximum floor, and the deleted floor will not affect other floors.

    {
            "_id" : ObjectId(),
            "comments_max_id" : int,
            "comments" : [
                    {
                            "id" : int,
                            "text" : "",
                    },
            ]
    }

    comments_max_id starts from 1 and is 0 when there are no comments
    When adding a new one, assign the new id and comments_max_id to comments_max_id+1 at the same time
    Deleting will not affect other replies

    reply
    0
  • 阿神

    阿神2017-04-21 11:19:54

    ObjectId() and the index of comments can determine a comment

    ObjectId() and 0 can be known to be the first reply to the article with id = ObjectId()

    If you need to manage all replies, use the method above

    reply
    0
  • ringa_lee

    ringa_lee2017-04-21 11:19:54

    You can create an auto-increment ID for a subdocument

    reply
    0
  • Cancelreply