Skip to content

Instantly share code, notes, and snippets.

@piglovesyou
Created July 26, 2014 06:41
Show Gist options
  • Save piglovesyou/62808db1c1a2a767306a to your computer and use it in GitHub Desktop.
Save piglovesyou/62808db1c1a2a767306a to your computer and use it in GitHub Desktop.
slow upsert in Sails.js
module.exports = {
attributes: {
/* e.g.
nickname: 'string'
*/
},
/**
* @param {Object} condition
* @param {Object} doc
* @return {Promise} passes Array.<Object>
*/
upsert: function(condition, doc) {
var that = this;
return this.findOne(condition)
.then(function(olddoc) {
return olddoc ?
that.update(condition, doc).toPromise() :
that.create(doc).then(function(doc) {
return [doc];
});
})
},
/**
* @param {Object} doc
* @return {Promise} passes document object
*/
upsertById: function(doc) {
var id = doc.id; // How do I get primaryKey.
var that = this;
return this.findOne(id)
.then(function(olddoc) {
return olddoc ?
that.update(id, doc).toPromise().get(0) :
that.create(doc).toPromise();
})
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment