Adding a mongoDB array element using Python Eve

Background: (using Eve and Mongo)

I am working in Python using the Eve REST provider library connecting to mongoDB to pull out several REST endpoints from the database. I still managed to use Eve, but I ran into a problem that might be slightly higher than what Eve can do initially.

My problem is that in my mongoDb document format there is a field (called "slots") whose value is a list / array of dictionaries / embedded documents.

Thus, the structure of the mongoDB document:

{
   blah1: data1,
   blah2: data2,
   ...
   slots: [
       {thing1:data1, thing2:data2},
       {thingX:dataX, thingY:dataY}
   ]
}

I need to add new entries (IE add pre-filled dictionaries) to the list of slots.

pymongo, :

mongo.connection = MongoClient()
mongo.db = mongo.connection['myDB']
mongo.coll = mongo.db['myCollection']

...

mongo.coll.update({'_id' : document_id}, 
                  {'$push': { "slot" : {"thing1":"data1","thingX":"dataX"}  }  } )

REST action/URI, , POST to '_id/slots', . URI /app/012345678901234567890123/slots.

: ( Eve)

SO: Python Eve eve project issue, , Eve mongoDB ( ?), , .


, ( , , )...


... , Eve/Flask , Eve mongoDB .

( ). Eve , _updated _etag, , .

Eve Datebase, , (I , , ).

- ? - ? (, Eve, Eve ( ) )

+4
1

. , :

  • .
  • Mongo.

, , , .


, , PATCH push, , . dict ({"slot": {"thing1": "data1", "thingX": "dataX"}}), :

'mycollection': {
    'type': 'list',
    'schema': {
        'type': 'dict',
        'schema': {
            'thing1': {'type': 'string'},
            'thingX': {'type': 'string'},
        }
    }
}

, (list type expected). , :

from eve.data.mongo.validation import Validator
from flask import request

class MyValidator(Validator):
    def validate_replace(self, document, _id, original_document=None):
        if self.resource = 'mycollection' and request.method = 'PATCH':
            # you want to perform some real validation here
            return True
        return super(Validator, self).validate(document)

, , .

PATCH. . , - ($set) . , , , . , , .


, $push $set, mycollection PATCH. - :

from eve.io.mongo import Mongo
from flask import request

class MyMongo(Mongo):
    def update(self, resource, id_, updates, original):
        op = '$push' if resource == 'mycollection' else '$set'
        return self._change_request(resource, id_, {op: updates}, original)

:

app = Eve(validator=MyValidator, data=MyMongo)
app.run()

; , , , .

push- Mongo. / , MONGO_UPDATE_OPERATOR/MONGO_UPDATE_OPERATOR, . $set, API . , - , , $push. , , , , , Eve 0.6 .

, .

+5

All Articles