使用Flask更新Document中的EmbeddedDocument - Mongoengine mongoengine.errors.OperationError

时间:2016-09-09 09:46:20

标签: python mongodb flask mongoengine

我正在开发一个带烧瓶和mongodb(mongoengine驱动器)的项目。该应用程序使用Note模型作为用户模态的embeddedDocument。

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)

当我尝试更新笔记时,没关系,但是然后尝试将更新的笔记附加到我坚持的用户集合中!

views.py

@app.route("/update_quote/<string:id>" ,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 )

回溯

   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 } ]}))

我认为这是我在下面写的重要部分。我没有找到关于它的任何问题,而且关于mongoengine的文档很少。我在哪里搜索?

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

1 个答案:

答案 0 :(得分:0)

这里有一些问题:

  • 您可以使用(在最新版本的mongoengine中)EmbeddedDocumentListField
  • Note类需要继承EmbeddedDocument
  • 您不能按照您尝试的方式对User对象使用更新操作

请考虑以下示例,该示例将向用户备注字段添加备注。

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

您可能还想阅读this answer,了解何时使用EmbeddedDocumentReferenceField