Eve - Is it possible to unset a key from a document?

痞子三分冷 提交于 2019-12-11 05:01:34

问题


In a schema with optional values such as code in the example:

'code': {
    'type': 'string',
},
'name': {
    'type': 'string',
    'required': True,
},
'email': {
    'type': 'string',
    'required': True
}

Let's say there's an inserted document with a value for code. Can I unset the code key like mongodb $unset does, using Eve somehow?


回答1:


One way to achieve this is to setup a default projection for the endpoint.

Limiting the Fieldset Exposed by the API Endpoint By default API responses to GET requests will include all fields defined by the corresponding resource schema. The projection setting of the datasource resource keyword allows you to redefine the fields.

people = {
    'datasource': {
        'projection': {'username': 1}
    }
}

The above setting will expose only the username field to GET requests, no matter the schema defined for the resource.

Another option is to leverage MongoDB Aggregation Framework itself. Just set the endpoint so that a aggregation is performed before data is returned to the client. The following should work (see the docs for details):

posts = {
    'datasource': {
        'aggregation': {
            'pipeline': [{"$unset": "code"}]
        }
    }
}

You need Eve v0.7 for aggregation support.



来源:https://stackoverflow.com/questions/39088047/eve-is-it-possible-to-unset-a-key-from-a-document

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