Skip to content

Commit

Permalink
feat: select only specified fields for return
Browse files Browse the repository at this point in the history
  • Loading branch information
jimlambie committed Feb 21, 2017
1 parent cce8af7 commit 51456ed
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
34 changes: 34 additions & 0 deletions lib/index.js
Expand Up @@ -134,6 +134,32 @@ DataStore.prototype.prepareQuery = function (query, options) {
return query
}

/**
* Determines the list of properties to select from each document before returning. If an array is specified
* it is returned. If an object is specified an array is created containing all the keys that have a value equal to 1.
* The `_id` property is added if not already specified.
*
* @param {Array|Object} fields - an array of field names or an object such as `{"title": 1}`
* @returns {Array} an array of property names to be selected from each document
*/
DataStore.prototype.getFields = function (fields) {
if (_.isEmpty(fields)) {
return null
}

var preparedFields

if (!Array.isArray(fields)) {
preparedFields = Object.keys(fields).filter((field) => { return fields[field] === 1 })
} else {
preparedFields = fields
}

if (!preparedFields['_id']) preparedFields.push('_id')

return preparedFields
}

/**
* Query the database
*
Expand All @@ -145,6 +171,8 @@ DataStore.prototype.prepareQuery = function (query, options) {
*/
DataStore.prototype.find = function (query, collection, options) {
options = options || {}
var fields = this.getFields(options.fields)

query = this.prepareQuery(query, options)

debug('find in %s %o %o', collection, query, options)
Expand All @@ -156,6 +184,12 @@ DataStore.prototype.find = function (query, collection, options) {

var results = res.docs

if (fields) {
results = _.chain(results)
.map((result) => { return _.pick(result, fields) })
.value()
}

return resolve(results)
})
}).catch((err) => {
Expand Down
2 changes: 1 addition & 1 deletion test/unit/couchdb.js
Expand Up @@ -136,7 +136,7 @@ describe('CouchDB', function () {
})
})

it.skip('should return only the fields specified by the `fields` property', function (done) {
it('should return only the fields specified by the `fields` property', function (done) {
var couchdb = new CouchDBAdapter()
couchdb.connect({ collection: 'users' }).then(() => {
var users = [{ name: 'Ernie', age: 7, colour: 'yellow' }, { name: 'Oscar', age: 9, colour: 'green' }, { name: 'BigBird', age: 13, colour: 'yellow' }]
Expand Down

0 comments on commit 51456ed

Please sign in to comment.