Question

I would like to append a new ListField EmbeddedDocument to an existing ListField EmbeddedDocument document. In other words appending a new document to list that belongs to a a document in list.

My Model: A Post can contain several Comments, each comment can have several Likes:

class Post(Document):
    txt = StringField()
    comments = ListField(EmbeddedDocumentField(Comment))

class Comment(EmbeddedDocument):
    comment = StringField()
    comment_id = ObjectIdField()
    likes = ListField(EmbeddedDocumentField(Like))

class Like(EmbeddedDocument):
    user = ReferenceField(User)
    date = DateTimeField(default=datetime.utcnow,required=True)

My Code: (it's not working 'append' command dosen't exists, only 'set' exists)

def appendNewLike():
    user = {..}
    target = ObjectId(commentId)
    newLike = Like(user=user)
    Product.objects(comments__comment_id=target).update(append_comments__S__likes=newLike)

Ideal solution would be something like:

def appendNewLike():
    user = {..}
    target = ObjectId(commentId)
    newLike = Like(user=user)
    Product.objects(comments__comment_id=target).comments.likes.append(newLike)

Comments? Suggestions?

Was it helpful?

Solution

You want to $push an new item to the list eg:

Post.objects(comments__comment_id=target).update(
    push__comments__S__likes=newLike
)

However, there are bigger issues here. The schema is not ideal - ever growing arrays might cause issues as the document grows it will have to be moved on disk to a new extent (so it can fit), if its continually growing then that will impact performance.

See the data modeling docs for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top