Created
December 3, 2011 14:46
-
-
Save wilsonpage/1427291 to your computer and use it in GitHub Desktop.
This function is run when a user changes any of their core data to update duplicates across the database.
This file contains hidden or 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
/** | |
* 'UpdateDuplicateData' | |
* | |
* Used to update user data on all models that it is duplicated on | |
* | |
* @param {object} User The main user model | |
* @param {object} changes An object containing the changed user attributes | |
* @param {Function} cb Callback - function(err){} | |
* | |
*/ | |
exports.updateDuplicateData = function(userID, changes, cb){ | |
userID = String(userID); | |
// I'm using async.js to run all the update functions in parrallel. | |
// When all these functions have finished the master callback function | |
// will be fired | |
async.parallel({ | |
updateFeedItems: function(cb){ | |
// make empty object | |
var mongoSet = {}; | |
// loop over each change and put it in the mongoSet object with 'user.' | |
// prepended so that it'll work with the mongo update query. | |
for(var prop in changes) mongoSet['user.' + prop] = changes[prop]; | |
// run the update query | |
DB.model('feeditems') | |
.update({'user._id': userID}, {'$set': mongoSet}, {multi: true}, cb); | |
}, | |
updateComments: function(cb1){ | |
console.log('updating comments...'); | |
// run the update query | |
DB.model('feeditems') | |
.find({'comments.user._id': userID}) | |
.run(function(err, feeditems){ | |
if(err) return cb1(err); | |
// if no feeditems found: return callback | |
if(!feeditems.length) return cb1(); | |
//[Loop] over each feeditem | |
async.forEach(feeditems, function(feeditem, cb2){ | |
//[Loop] over each of the feeditem's comments | |
async.forEach(feeditem.comments, function(comment, cb3){ | |
// if this isn't one of the user's comments: return | |
if(String(comment.user._id) !== userID) return cb3(); | |
// extend the user object with the new changes | |
myUtils.extend(comment.user, changes); | |
//[Callback] | |
cb3(); | |
// COMMENT LOOP FINISHED | |
}, function(err){ | |
if(err) return cb2(err); | |
//[Callback] save the feeditem | |
feeditem.save(cb2); | |
}); | |
// FEEDITEM LOOP FINISHED | |
}, cb1); | |
}); | |
} | |
}, cb); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment