Dave Roma
Dave Roma

Reputation: 2679

Remove a ListField item by id using Mongoengine

I'm trying to remove an item from a ListField by targeting the list item's _id using mongoengine - I'm referring to the mongoengine docs on atomic updates here: http://docs.mongoengine.org/guide/querying.html#atomic-updates

Model

class Prospect(db.Document):
  comments          = db.ListField(db.EmbeddedDocumentField('Comment'))

class Comment(db.EmbeddedDocument):
  _id             = db.ObjectIdField(default=bson.ObjectId())
  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)

Mongo document looks like this:

...
"comments": [
      {
        "_id": {
            "$oid": "53bebb55c3b5a0db7829c15f"
        },
        "created_at": {
            "$date": "2014-07-09T18:26:58.444Z"
        },
        "body": "Did something\n",
        "author": "Dave Roma"
    },

And Im trying to remove a comment like so:

prospect = Prospect.objects(id=request.form['prospect_id']).update_one(pull___id=request.form['comment_id'])

And I'm receiving a mongoengine invalidQueryError:

InvalidQueryError: Cannot resolve field "_id"

Upvotes: 1

Views: 3688

Answers (1)

shshank
shshank

Reputation: 2641

The answer to your question will be:

prospect = Prospect.objects(id=request.form['prospect_id']).update_one(pull__comments__id=request.form['comment_id'])

Your original query was trying to find _id field in mongoengine which obviously didn't exist.

And now the solution to the problem you talked about in comment.

Solution 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)

The above solution may fail if two clients try to add new post at the same time. They might have sam e _id. There is no way to enforce uniqueness in the embedded document fields in mongo. You can only do that with client code.

Solution 2:

Make a separate comments collection.

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')

This was unique id will be given to each comment.

Solution 3:

This is just an Idea, I am not sure about pros and cons.

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

Upvotes: 1

Related Questions