Skip to content

Instantly share code, notes, and snippets.

@danielstreit
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielstreit/712333643a658cf17bd3 to your computer and use it in GitHub Desktop.
Save danielstreit/712333643a658cf17bd3 to your computer and use it in GitHub Desktop.
Add a star to a collection given a user
var addStar = function(data) {
return $http({
method: 'POST',
url: '/api/collection/addStar',
data: data
}).then(function(response) {
return response.data;
});
};
// If the provided user has not already starred this
// collection, adds a star to the collection
//
// Expects data to have _id and user properties:
// {
// _id: the collection to add to
// user: [
// {
// provider: String,
// id: String,
// fullName: String,
// givenName: String
// }
// ]
// }
// Returns a promise that resolves to the updated collections
mongo.addStar = function(data) {
// Stringify the user
// This should be unique to every user
var userString = data.user.provider + data.user.id;
return Collection.findByIdAndUpdate(data._id, {
$addToSet: { userStars: userString }
}).exec()
.then(function(collection) {
var update = {};
update._id = collection._id;
update.stars = collection.userStars.length;
return mongo.update(update);
});
};
// add a star to a collection
// this will check if the given user has already stared the collection
// and if not, add the user to userStars and increment stars.
// responds with the collection, updated or not
app.post('/api/collection/addStar', function(req, res) {
mongo.addStar(req.body).then(function(collection) {
res.end(JSON.stringify(collection));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment