Last active
February 23, 2017 15:01
-
-
Save jamesholcomb/2db8ad58cfcc3985ced28dd48eebc501 to your computer and use it in GitHub Desktop.
A feathers.js before create hook to handle Mongoose upserts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use this hook to manipulate incoming or outgoing data. | |
// For more information on hooks see: http://docs.feathersjs.com/hooks/readme.html | |
import fromPairs from 'lodash/fromPairs' | |
import map from 'lodash/map' | |
/** | |
* upsert | |
* Executes upsert on a Mongoose model | |
* Configure in your service as a before:create hook | |
* Note: Update hooks will not fire as a result | |
* @arg {String} serviceName The feathers service name | |
* @arg {Array} keyNames The model key field names | |
* @return {Promise} The resolved hook | |
*/ | |
module.exports = function (serviceName, keyNames) { | |
return function (hook) { | |
const service = hook.app.service(serviceName) | |
const pairs = keyNames.map((field) => ({ | |
key: field, | |
val: hook.data[field] | |
})) | |
const query = fromPairs(map(pairs, i => [i.key, i.val])) | |
return service.Model.findOneAndUpdate(query, | |
{ $set: hook.data }, { | |
new: true, | |
upsert: true | |
}).exec().then((res) => { | |
hook.result = res | |
return hook | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment