updating EmbeddedDocument in Document with Flask - Mongoengine mongoengine.errors.OperationError
<p>I am developing a project with flask and mongodb(mongoengine drive). The application uses Note model as a embeddedDocument for User Modal.</p>

<pre><code>class User(db.Document, UserMixin):
    fields like created_at, content, slug etc...
    notes = db.ListField(db.EmbeddedDocumentField('Note'))

class Note(db.Document):
     fields like created_at, content, slug, URLLink, isSecret etc...
     content = db.StringField(required=True)
     tags = db.ListField(db.StringField(required=True, max_length=20)
</code></pre>

<p>When I try to Update a Note it's okay, but then trying to append the updated note in the User collection I stucked!</p>

<p><strong>views.py</strong></p>

<pre><code>@app.route("/update_quote/&lt;string:id&gt;" ,methods=['POST'])
@login_required
def update_quote(id):
    note = Note.objects(id=id).first()

    form = UpdateNoteForm()
    if request.method == 'POST':
        form = UpdateNoteForm(request.form)

        if form.validate == False:
            flash('Faliure','danger')
            return redirect(url_for('profile')+('/'+current_user.slug))

        if form.validate_on_submit():

            tags = form.tags2.data
            tagList = tags.split(",")

            note = Note.objects.get(id=form.wtf.data)
            note.update(content=form.content2.data, tags=tagList, URLLink=form.URLLink2.data)

            current_user.notes.append(note)
            current_user.update(notes__tags=tagList, notes__content=form.content2.data, notes__URLLink=form.URLLink2.data)

            flash("Success","success")

    return render_template("update.html", title="delete", form=form, note=note )
</code></pre>

<p><strong>traceback</strong></p>

<pre><code>   mongoengine.errors.OperationError
OperationError: Update failed (cannot use the part (notes of notes.URLLink) to traverse the element ({notes: [ { _id: ObjectId('57d27bb24d2e9b04e175c0e5'), created_at: new Date(1473422818025), URLLink: "", content: "{
    "_id" : ObjectId("57d27b414d2e9b04d79883b3"),
    "created_at" : ISODate("2016-09-09T12:05:05.164Z"),
    "URLLink" : "",
    "content" : "c...", tags: [ "asd" ], isSecret: false, isArchived: false } ]}))

Traceback (most recent call last)
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/flask_login.py", line 792, in decorated_view
return func(*args, **kwargs)
File "/Users/ozer/Google Drive/localhost/copylighter/views.py", line 225, in update_quote

                        note = Note.objects.get(id=form.wtf.data)
                        note.update(content=form.content2.data, tags=tagList, URLLink=form.URLLink2.data)

                        current_user.notes.append(note)
                        current_user.update(notes__tags=tagList, notes__content=form.content2.data, notes__URLLink=form.URLLink2.data)


                        #note.save()


File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/mongoengine/document.py", line 468, in update
return self._qs.filter(**self._object_key).update_one(**kwargs)
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 490, in update_one
upsert=upsert, multi=False, write_concern=write_concern, **update)
File "/Users/ozer/Documents/localhost/copylighter/env/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 472, in update
raise OperationError(u'Update failed (%s)' % unicode(err))
OperationError: Update failed (cannot use the part (notes of notes.URLLink) to traverse the element ({notes: [ { _id: ObjectId('57d27bb24d2e9b04e175c0e5'), created_at: new Date(1473422818025), URLLink: "", content: "{ "_id" : ObjectId("57d27b414d2e9b04d79883b3"), "created_at" : ISODate("2016-09-09T12:05:05.164Z"), "URLLink" : "", "content" : "c...", tags: [ "asd" ], isSecret: false, isArchived: false } ]}))
</code></pre>

<p>I think that's the important part that I writed below. I didn't find any quertset about it and there are few documentation about mongoengine. Where would I search for?  </p>

<pre><code>current_user.update(notes__tags=tagList, notes__content=form.content2.data, notes__URLLink=form.URLLink2.data)
</code></pre>

<p>You have a few issues here:</p>

<ul>
<li>You can use (in the most recent versions of mongoengine) an <a href="http://mongoengine-odm.readthedocs.io/apireference.html#mongoengine.fields.EmbeddedDocumentListField" rel="nofollow">EmbeddedDocumentListField</a></li>
<li>The <code>Note</code>class needs to inherit EmbeddedDocument </li>
<li>You can't use an update operation on the <code>User</code> object in the way you are attempting</li>
</ul>

<p>Consider the following example which will add a note to the users note field.</p>

<pre><code>import mongoengine as mdb
from numpy.random.mtrand import randint

mdb.connect("embed-test")


class User(mdb.Document):
    name = mdb.StringField()
    notes = mdb.EmbeddedDocumentListField('Note')


class Note(mdb.EmbeddedDocument):
    content = mdb.StringField(required=True)
    tags = mdb.ListField(mdb.StringField(required=True, max_length=20))


User.drop_collection()

u = User(name="Name").save()

if __name__ == "__main__":
    new_note = Note(content="Some notes here.", tags=['one', 'two'])
    current_user = User.objects.first()
    current_user.notes.append(new_note)
    current_user.save()
</code></pre>

<p>You may also want to read <a href="http://stackoverflow.com/questions/34897566/mongoengine-embeddeddocument-v-s-referencefield/34952982#34952982">this answer</a> on when to you use <code>EmbeddedDocument</code> vs. a <code>ReferenceField</code>. </p>

python mongodb flask mongoengine