closeio / flask-mongorest

Restful API framework wrapped around MongoEngine
Other
523 stars 88 forks source link

Error: A ReferenceField only accepts DBRef, ObjectId or documents #113

Open Vayel opened 7 years ago

Vayel commented 7 years ago

Hi!

I have the following models:

class Document(db.Document):
    title = db.StringField(required=True,)

class Collection(db.Document):
    # Some fields
    # ...
    documents = db.ListField(db.ReferenceField(Document))

Then I defined my API the simplest way:

class DocumentResource(Resource):
    document = Document

@api.register(name='documents', url='/documents/')
class DocumentView(ResourceView):
    resource = DocumentResource
    methods = [methods.Create, methods.Update, methods.Fetch, methods.List]

class CollectionResource(Resource):
    document = Collection

@api.register(name='collections', url='/collections/')
class CollectionView(ResourceView):
    resource = CollectionResource
    related_resources = {
        'documents': DocumentResource,
    }
    methods = [methods.Create, methods.Update, methods.Fetch, methods.List]

After filling the db with mongoengine, I request http://127.0.0.1:5000/collections/593719c2b15ab34148e85c59/:

{
    "documents": [
        "59383fbeb15ab314ca83a553"
    ],
    "id": "593719c2b15ab34148e85c59",
    "title": "qsdhv qs 456 Js"
}

But when I make an AJAX call to the API to add a document to the collection, I obtain the error {"field-errors": {"documents": {"0": "A ReferenceField only accepts DBRef, ObjectId or documents", "1": "A ReferenceField only accepts DBRef, ObjectId or documents"}}}.

If I use a list of ObjectIdFields instead of a ReferenceFields for models.Collection.documents, it works. But if I add a List(MongoReferenceDocument) constraint in the schema of CollectionRessource, it does not work anymore.

I only have the error with the PUT method. When I fill the documents attribute in a POST request, it works.

Thanks