您的问题的答案将是:
prospect = Prospect.objects(id=request.form['prospect_id']).update_one(pull__comments__id=request.form['comment_id'])
您的原始查询试图_id
在 mongoengine 中查找显然不存在的字段。
现在解决您在评论中谈到的问题。
解决方案1:
class Prospect(db.Document):
comments = db.ListField(db.EmbeddedDocumentField('Comment'))
def get_next_comment_id(self):
return len(self.comments)+1
def add_new_comment(self, author, body):
self.update(add_to_set__comments=Comment(_id=self.get_next_comment_id(), author=author, body=body)
class Comment(db.EmbeddedDocument):
_id = db.IntField(required=True)
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
body = db.StringField(verbose_name="Note", required=True)
author = db.StringField(verbose_name="Name", max_length=255, required=True)
如果两个客户端同时尝试添加新帖子,上述解决方案可能会失败。他们可能有相同的_id。无法在 mongo 中的嵌入文档字段中强制执行唯一性。您只能使用客户端代码执行此操作。
解决方案2:
制作单独的评论集。
class Prospect(db.Document):
comments = db.ListField(db.EmbeddedDocumentField('Comment'))
class Comment(db.Document):
on_prospect = db.ReferenceField(Prospect)
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
body = db.StringField(verbose_name="Note", required=True)
author = db.StringField(verbose_name="Name", max_length=255, required=True)
def add_new_comment(prospect, author, body):
comment = Comment(on_prospect = prospect, author=author, body=body).save()
return comment.id
def get_all_posts_on_prospect(prospect):
return Comment.objects(on_prospect = prospect).order_by('-id')
这是每个评论的唯一 ID。
解决方案3:
这只是一个想法,我不确定利弊。
class Prospect(db.Document):
comments = db.ListField(db.EmbeddedDocumentField('Comment'))
def get_id_for_comment(self, comment):
return self.comments.index(comment)
class Comment(db.EmbeddedDocument):
_id = db.IntField()
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
body = db.StringField(verbose_name="Note", required=True)
author = db.StringField(verbose_name="Name", max_length=255, required=True)
def add_new_comment(prospect, author, body)
comment = Comment(_id=self.get_next_comment_id(), author=author, body=body)
prospect.update(add_to_set__comments = comment)
cid = prospect.get_id_for_comment(comment)
prospect.update(set__comments__cid__id = cid)
return cid