InvalidDocument: Cannot encode object: Refe

2019-09-07 15:41发布

问题:

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
    )