InvalidDocument: Cannot encode object: <User: User object> ReferenceField with MongoEngine

怎甘沉沦 提交于 2019-12-12 03:59:56

问题


I've been working with Flask and MongoEngine, and I am having trouble when trying to save an object because of a ReferenceField.

This is what my model looks like:

class User(UserMixin, db.Document):
    first_name = db.StringField(max_length=255, required=True)
    last_name = db.StringField(max_length=255, required=True)
    email = db.StringField(max_length=255)

class Post(db.Document):
    description = db.StringField(max_length=255, required=True)
    inserted_at = db.DateTimeField(default=datetime.datetime.now, required=True)
    tags = db.ListField(db.EmbeddedDocumentField('Tag'))
    comments = db.ListField(db.EmbeddedDocumentField('Comment'))
    user = db.ReferenceField('User')

This is how I create the Post object:

    user = User.objects.filter(id=current_user.id).first()

    post = Post(
        description = request.json["description"],
        user = user
    )

I have also tried:

user = current_user._get_current_object()

But I keep getting:

InvalidDocument: Cannot encode object: <User: User object>

Any ideas on what's going on?

Thanks!


回答1:


I think there is some issue with the db module you are using. Is it really the mongoengine module. Because your code works fine, if I use

import mongoengine as db



回答2:


Well, this is from a long time, but I got the same problem. I don't know if it's for different reasons, but the context does look very similar.

Anyway, it looks like the current_user object is a LocalProxy instance which does not play well with mongoengine. The trick was to "force" dereference the ObjectID of the instance, like this:

post = Post(
        description = request.json["description"],
        user = user.id
    )


来源:https://stackoverflow.com/questions/32746284/invaliddocument-cannot-encode-object-user-user-object-referencefield-with-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!