Getting an object within a query in MongoDB - javascript

I'm using MongoDB for the first time and having some difficulty. I'm trying to get an object from the database and then set properties of this object to be other objects in the database.
app.get('/photoCollection/:id', function (request, response) {
var id = request.params.id;
var query = Photos.find({user_id: id});
query.select("_id user_id comments file_name date_time").exec(function(err, info) {
if (info === null) {
console.error('Photos for user with _id:' + id + ' not found.');
response.status(400).send('Not found');
}
infoParsed = JSON.parse(JSON.stringify(info));
for (let i = 0; i < infoParsed.length; i++) {
for (let j = 0; j < infoParsed[i].comments.length; j++) {
let commenter_id = infoParsed[i].comments[j].user_id;
delete infoParsed[i].comments[j].user_id;
let commenterQuery = User.findOne({_id: commenter_id});
let commenter;
commenterQuery.select("_id first_name last_name").exec(function(err, info) {
commenter = info;
});
infoParsed[i].comments[j].user = commenter;
}
}
response.status(200).send(infoParsed);
});
});
I've tried this a few ways, and with this way (my most recent try), I'm getting the commenter is undefined. I haven't seen queries used like this, so I'm not surprised, but I was wondering if there was a better way to get something from the database during a query. Any help would be appreciated!

Related

nodejs express sent object not synchronized with front end

I am trying to send an object from nodejs server to the front end but one property is keep getting deleted on the way
server
router.post('/cart/retrieve', (req, res) => {
let cart = req.session.cart;
let prodId = Object.keys(cart);
Product.find({_id: {$in: prodId}}, (err, result) => {
if (err) throw err;
let resultToSend = [];
for (let i = 0; i < result.length; i++) {
let curResult = result[i];
curResult['cartQuantity'] = parseInt(cart[curResult._id]);
result[i] = curResult;
}
resultToSend = result;
console.log(resultToSend[0]['cartQuantity'])
res.json({cart: resultToSend})
});
});
frontend
$("#top-cart-trigger").click(function(e){
$.post('/api/shop/cart/retrieve',{
}, function (returnResult) {
console.log(returnResult['cart'][0]['cartQuantity'])
let products = returnResult['cart'];
console.log(returnResult)
for(let i = 0; i < products.length; i ++){
let curProduct = products[i];
console.log(curProduct['cartQuantity'])
}
});
});
so practically the json variable sent from server and the returnResult received from the front end are same variables. However, my console.log(resultToSend[0]['cartQuantity']) returns 3 (which is correct) but console.log(curProduct['cartQuantity']) is undefined for all elements. What am I doing wrong?
I think the problem might comes from mutable variable result in your server.
However it seems like the variable returnResult['cart'] is JSON and you are expecting array. You could use 'for in' instead. See https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Statements/for...in
Just try to replace for loop with this
for (let key in returnResult['cart']){
console.log(returnResult['cart'][key]['cartQuantity']);
}

How to Save multiple messages in Azure Function JavaScript?

I have created one Azure function in Azure app which is triggered by IOT Hub, and it saves received messages in SQL database. but it is not able to handle when it receives multiple messages. my function is bellow.
module.exports = function (context, iotHubMessage) {
for (var i = 0; i < iotHubMessage.length; i++) {
var iotMsgObj = iotHubMessage[i];
context.log('Message : ' + JSON.stringify(iotMsgObj));
context.bindings.paraSession = JSON.stringify(iotMsgObj); //to save data in SQL database
context.done(); // will save first message only
}
// context.done(); // will save last message only
};
when iotHubMessage hub has multiple JSON objects, it will save ether first or last message from iotHubMessage will store in database table.
please advice what I am doing wrong?
I haven't tried with SQL binding, but returning an array works for other types (e.g. queue):
module.exports = function (context, iotHubMessage) {
context.bindings.paraSession = [];
for (var i = 0; i < iotHubMessage.length; i++) {
var iotMsgObj = iotHubMessage[i];
context.bindings.paraSession.push(JSON.stringify(iotMsgObj));
}
context.done();
};
Mikhail is right if you are storing data in Azure Table Storage. But when you are using SQL Database you need the following code snippet.
module.exports = function (context, iotHubMessage) {
var tempArr = [];
for (var i = 0; i < iotHubMessage.length; i++) {
var iotMsgObj = iotHubMessage[i];
tempArr.push(iotMsgObj);
}
context.bindings.paraSession = tempArr;
context.done();
};

How can I check if two array contains the same value, even if they are in different indexes?

I'm working on a personal project and I'm stump in the last part. I'm trying to only get the data for companies that have the same name of the companies in my database.
My goal at the end is to merge the two jsons obtained from the two following calls into one
Call one: $http.get('//localhost:8081/api/jobs').then(function(res)
Call two: localhost:8081/api/glassdoor/
Full Code:
$http.get('//localhost:8081/api/jobs').then(function(res) {
$scope.data = res.data; //data from the database
$scope.size = $scope.data.length; //length 132
for (var i = 0; i < $scope.size; i++) {
if ($scope.data[i].glassdoor !== null && $scope.data[i].glassdoor !== undefined) {
$scope.hasGlassdoor = [];
for (var i = 0; i < $scope.size; i++) {
if ($scope.data[i].glassdoor !== null && $scope.data[i].glassdoor !== undefined)
$scope.hasGlassdoor.push($scope.data[i]);
}
//Get the companies name that have glassdoor
$scope.company = [];
for (var j = 0; j < $scope.hasGlassdoor.length; j++) {
$scope.company.push($scope.hasGlassdoor[j].company);
}
//Create the URL calls for my glassdoor api
$scope.url = [];
for (var x = 0; x < $scope.company.length; x++) {
$scope.url.push('//localhost:8081/api/glassdoor/' + $scope.company[x]);
}
//For example : '//localhost:8081/api/glassdoor/A9.com'
//Get the Glassdoor data
var company = $scope.company;
for (var j = 0; j < $scope.url.length; j++) {
$http.get($scope.url[j]).then(function(response) {
$scope.gData = response.data;
$scope.gSize = $scope.gData.length;
$scope.gName = [];
//Get the names of the companies that glassdoor returns
for(var x = 0; x < $scope.gSize; x++){
if ($scope.gData[x] !== null && $scope.gData[x] !== undefined) {
if ($scope.gData[x].name !== null && $scope.gData[x].name !== undefined) {
$scope.gName.push($scope.gData[x].name);
}
}
}
//Now I'm trying to only get the names of the companies that are in my variable company
//For example '//localhost:8081/api/glassdoor/6sense
//returns data for 6sense, and a company named 6sense Technologies
//I'm trying to just get the data of 6sense
//
// TODO
//
// My try using loDash returns undefined.
// I'm trying to see if $scope.gName is in var Company.
//if(_.includes(company, $scope.gName)){
// gd.push($scope.gName);
//}
}); //this is what is calling the glassdoor api
}//end of the for loop for url.
} //if statement to check for null
} //first for loop
}).catch(function(error, res) {
console.log("Error:", error, res);
});
Right now I'm working on small list so I can fix this issue.
My goal at the end is to have this as my finished json:
[
{
"company": "23andMe"
"glassdoor":"https://www.glassdoor.com/Overview/Working-at-23andMe-EI_IE145899.11,18.htm"
"img":"https://www.23andme.com/static/img/icons/logo_alt.96cf7888b73d.svg"
"international":null
"link":"https://www.23andme.com/careers/"
"location":"Mountain View, CA"
"secondary":null
"third":null
"id":145899,
"name":"23andMe",
"website":"www.23andme.com",
"isEEP":true,
"exactMatch":true,
"industry":"Biotech & Pharmaceuticals",
"numberOfRatings":27,
"squareLogo":"https://media.glassdoor.com/sqll/145899/23andme-squarelogo.png",
"overallRating":"4.2",
"ratingDescription":"Very Satisfied",
"cultureAndValuesRating":"4.5",
"seniorLeadershipRating":"3.6",
"compensationAndBenefitsRating":"4.0",
"careerOpportunitiesRating":"3.4",
"workLifeBalanceRating":"4.3",
"recommendToFriendRating":80,
"sectorId":10005,
"sectorName":"Biotech & Pharmaceuticals",
"industryId":200021,
"industryName":"Biotech & Pharmaceuticals",
"featuredReview":{
"attributionURL":"https://www.glassdoor.com/Reviews/Employee-Review-23andMe-RVW11447587.htm",
"id":11447587,
"currentJob":true,
"reviewDateTime":"2016-08-03 15:05:20.157",
"jobTitle":"Customer Care Reporesentative",
"location":"Mountain View, CA",
"jobTitleFromDb":"Customer Care Reporesentative",
"headline":"Customer Care Representative",
"pros":"the environment-everyone is extremely genuine, smart, and friendly. management is very understanding and open. Executives are transparent with everything going on in the company\r\nbenefits-free gym, food every day, snacks, great health coverage, rooftop access, etc\r\nworkspace-facilities does a phenomenal job at keeping everything extremely clean and fixes all issues ASAP. I don't feel like I'm sitting a boring desk job all day, it's a fun place to be",
"cons":"Traffic through downtown mountain view can suck and the train can be kind of loud (I cannot think of a legitimate con, everything is awesome here)",
"overall":5,
"overallNumeric":5
},
"ceo":{
"name":"Anne Wojcicki",
"title":"CEO",
"numberOfRatings":15,
"pctApprove":100,
"pctDisapprove":0
}
}
]
Server.js that deals with the glassdoor call:
//Glassdoor api call
app.get('/api/glassdoor/:company', function(req, res, next) {
var company = req.params.company;
requestify.get('https://api.glassdoor.com/api/api.htm?t.p=PRODUCT&t.k=KEY&userip=0.0.0.0&useragent=&format=json&v=1&action=employers&q=' + company).then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
gData = response.getBody();
gData = gData.response.employers;
res.json(gData);
});
});
Sort the array, then enumerate it. If previous === current you have a dupe.
This is how I solved it.
app.get('/api/glassdoor/:company', function(req, res, next) {
var company = req.params.company;
requestify.get('https://api.glassdoor.com/api/api.htm?t.p=PRODUCT&t.k=KEY&userip=0.0.0.0&useragent=&format=json&v=1&action=employers&q=' + company).then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
gData = response.getBody();
gData = gData.response.employers;
//What I added to only send the data of the companies that where like 'company'
for (var i = 0; i < gData.length; i++) {
if (gData[i].name === company) {
gData = gData[i];
res.send(gData);
}
}
});
});
Which doesn't answer the overall question but that is how I solved my particular issue.

javascript - get items with query and match items to a user who has favorited item

I am writing a script on parse.com's javascript cloud code SDK. Here is the information I have saved in my parse.com account and what I am trying to do with it.
I have a bunch of items saved in a parse class called TestItem, theses items have an objectId, item name, meal time (lunch, dinner) and a location for there columns. I also have a class called UserFavourites. In this class the objects have an objectId, item name and a pointer to the user who saved the item as a favourite.
And with this information I am trying to write a cloud code script in javascript. That will match the an item(s) to the item(s) that a user has favourited and send them a push notification saying where and what the item is and the location of the item. I have some code that will do that but this code will send a different notification for each item which could get annoying for the user here is that code.
Parse.Cloud.define("push", function(request, response) {
var TestItem = Parse.Object.extend("TestItem");
var query = new Parse.Query(TestItem);
query.limit(1000);
query.equalTo('school', 'Union College (NY)');
query.find({
success: function(resultsItem) {
//console.log("Successfully retrieved " + resultsItem.length + " :1111.");
for (var i = 0; i < resultsItem.length; i++) {
var object = resultsItem[i];
var item = object.get('item');
var school = object.get('school');
var meal = object.get('meal');
var meal = meal.toLowerCase();
var diningLocation = object.get('schoolMenu');
//var itemArray = [];
var UserFavourite = Parse.Object.extend("UserFavourite");
var queryFavourite = new Parse.Query(UserFavourite);
queryFavourite.limit(1000);
queryFavourite.equalTo("item", item)
queryFavourite.equalTo("school", school)
queryFavourite.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var objectFav = results[i];
var user = objectFav.get('user');
var userID = user.id;
var realItem = objectFav.get('item');
console.log(objectFav.get('user'));
console.log(objectFav.get('item'));
var UserClass = Parse.Object.extend("User");
var queryUser = new Parse.Query(UserClass);
queryUser.get(userID, {
success: function(userResult) {
console.log(userResult.get('school'));
console.log('install:' + userResult.get('installation').id);
var userInstallationId = userResult.get('installation').id;
var queryInstallation = new Parse.Query(Parse.Installation);
queryInstallation.equalTo('objectId', userInstallationId);
queryInstallation.find({
success: function(results) {
console.log('number' + results.length);
Parse.Push.send({
// deviceType: [ "ios" ],
where: queryInstallation,
data: {
alert: realItem + " is being served at " + diningLocation + " for " + meal
}
},
{
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
},
error: function(error) {
console.log('error');
}
});
},
error: function(error) {
console.log('error');
}
});
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
As you can see it is quite long and not very nice looking, I tried to save items to an array so to avoid sending two or more notifications but couldn't get that to work.
So I started writing another script that uses promises which looks much nicer but haven't gotten it all the way right now, it can match the items to users that have an item favourited and put the objectId's of those users in an array. Here is that code.
Parse.Cloud.define("test", function(request, response) {
var UserFavourite = Parse.Object.extend("UserFavourite");
var queryFavourite = new Parse.Query(UserFavourite);
var userArray = [];
var TestItem = Parse.Object.extend("TestItem");
var query = new Parse.Query(TestItem);
query.limit(1000);
query.equalTo('school', 'Union College (NY)');
query.find().then(function(results) {
return results;
}).then(function(results) {
var promises = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
var item = object.get('item');
var school = object.get('school');
var meal = object.get('meal');
var UserFavourite = Parse.Object.extend("UserFavourite");
var queryUser = new Parse.Query(UserFavourite);
queryUser.equalTo("item", item);
queryUser.equalTo("school", school);
var prom = queryUser.find().then(function(users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
var userID = user.get('user').id;
if (userArray.indexOf(userID) === -1) {
userArray.push(userID);
}
}
return userArray;
});
promises.push(prom);
}
return Parse.Promise.when.apply(Parse.Promise, promises);
}).then(function(results) {
console.log(userArray);
});
});
But now with this code I don't know where to go, I think using promises and such is the right way to go but I am now confused as once I have all the users that have an item favourited what to do, I then need to get there items that are favourited and are available in the TestItem class, this is where I am struggling.
Here is a pic of my UserFavourite class it has a pointer to the user who favorited the item as you can see, and also a user has more than one favorite.
Thanks a bunch for the help in advance.
Here is your code, and I changed a couple things.
Parse.Cloud.define("getAllFavoriteItems", function (request, response) {
var TestItems = Parse.Object.extend("TestItems");
var UserFavorites = Parse.Object.extend("UserFavorites");
var testItemsQuery = new Parse.Query(TestItems);
var userFavoritesQuery = new Parse.Query(UserFavorites);
testItemsQuery.equalTo('school', 'Union College (NY)');
userFavoritesQuery.include('testItems'); //This makes sure to pull all of the favorite item data instead of just the pointer object
userFavoritesQuery.matchesQuery('testItem', testItemsQuery); //This will run this second query against the TestItems
userFavoritesQuery.limit(1000); //limit results to 1000
userFavoritesQuery.ascending('userId'); //group the user id's together in your array
userFavoritesQuery.find({
success:function(results) {
var pushNotificationMessage = "";
var userId = "";
for (var i=0; i <results.length; i++) {
if (results[i].get('userId') != userId) {
if (results[i].get('userId') != "") {
//TODO send push notification
}
userId = results[i].get('userId');
pushNotificationMessage = ""; //start a new push notification
}
pushNotificationMessage += results[i].get('item').get('name') + ": " + results[i].get('item').get('location') + "\n";
//SOMEWHERE BEFORE HERE I NEED THE INSTALLATION ID OF THE USER
//TO SEND THE PUSH TO THAT USER
Parse.Push.send({
// deviceType: [ "ios" ],
where: queryInstallation,
data: {
alert: pushNotificationMessage
}
},
{
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
}
response.success(true);
},
error:function(error) {
response.error();
}
})
});
Some code that might create push per user, rough outline though
if (i > 0) {
if (results[i].get('user') === results[i-1].get('user')) {
userItems.push(results[i]);
}
else {
userItems.length = 0;
}
}
else {
userItems.push(results[i]);
}
Not sure let me know if you understand what I'm trying to do...
So it a user has two items favourited I want it to group that into one, phrase that says what and where both items are being served
And here is code to send push
Parse.Push.send({
// deviceType: [ "ios" ],
where: queryInstallation,
data: {
alert: pushNotificationMessage
}
},
{
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
It can also be done with then/ promises,
I agree with #Maxwell that your UserFavorite should have links to both User and TestItem. This makes it possible to make your cloud-function as simple as:
Parse.Cloud.define("getAllFavoriteItems", function(request, response) {
var TestItem = Parse.Object.extend("TestItem");
var UserFavorites = Parse.Object.extend("UserFavorites");
var testItemsQuery = new Parse.Query(TestItem);
var userFavoritesQuery = new Parse.Query(UserFavorites);
testItemsQuery.equalTo('school', request.params.school);
userFavoritesQuery.include('testItem');
userFavoritesQuery.include('user');
userFavoritesQuery.matchesQuery('testItem', testItemsQuery); //This will run this second query against the TestItems
userFavoritesQuery.find().then(function(results) {
var alerts = {};
for(var i =0 ; i<results.length; i++ ){
var user = results[i].get('user');
var testItem = results[i].get('testItem');
if(user && testItem){
var instId = user.get('installationId');
if(!alerts[instId]) {
alerts[instId] = [];
}
var m = results[i].get('item') + " is being served at {{diningLocation}} for " + testItem.get('meal');
alerts[instId].push(m);
}
}
response.success(alerts);
}, function(error) {
response.error();
});
});
This is working code that you can also find in my github repo.
You can also see the working demo here
The idea is the same as in Maxwell's answer: to have link in UserFavorites class to both User (where installationId is located) and TestItem entities. I've just made it working by including user and testItems properties in query, so when the result is returned filtered by school name I already have a list of installationIds.
Here is my schema:
User
TestItem
UserFavorites
Update:
In this code I added push notifications:
Parse.Cloud.define("getAllFavoriteItems", function(request, response) {
var TestItem = Parse.Object.extend("TestItem");
var UserFavorites = Parse.Object.extend("UserFavorites");
var testItemsQuery = new Parse.Query(TestItem);
var userFavoritesQuery = new Parse.Query(UserFavorites);
testItemsQuery.equalTo('school', request.params.school);
function SendPush(installationId, msg) {
var query = new Parse.Query(Parse.Installation);
query.equalTo('objectId', installationId);
Parse.Push.send({
where: query,
data: {alert: msg}
});
}
userFavoritesQuery.include('testItem');
userFavoritesQuery.include('user');
userFavoritesQuery.matchesQuery('testItem', testItemsQuery); //This will run this second query against the TestItems
userFavoritesQuery.find().then(function(results) {
var groupedAlerts = {};
// manually iterating though results to get alert strings ang group by user in groupedAlerts[installationId]
for(var i =0 ; i<results.length; i++ ){
var user = results[i].get('user');
var testItem = results[i].get('testItem');
if(user && testItem){
var instId = user.get('installationId');
if(!groupedAlerts[instId]) {
groupedAlerts[instId] = [];
}
var m = results[i].get('item') + " is being served at {{dining Location}} for " + testItem.get('meal');
groupedAlerts[instId].push(m);
}
}
// reformat to array and send push notifications
var alerts = [];
for(var key in groupedAlerts) {
alerts.push({
installationId: key,
alerts: groupedAlerts[key],
});
// Send push notifications
SendPush(key, groupedAlerts[key].join());
}
response.success(alerts);
}, function(error) {
response.error();
});
});
I've also updated test data in live demo (just press Get Alerts) or feel free to play around with test data hot it changes cloud code response. gitnub repo is also up to up to date.
This is based on what I understand as the problem you're trying to solve. If it's not addressing the right issue, let me know and I'll see what I can do.
Looking first at your database model, we can simplify this a bit by modifying the UserFavorites table. Starting with the initial two classes, you have a table of items and a table of users. Since a user can favorite many items and an item can be favorited by many users, we have a many-to-many relationship that exists. When this happens, we need to make a third class that points to each of the other two classes. This is where the UserFavorites table comes into play. In Parse terms, the UserFavorites table needs to have two pointers in it: one for the user and one for the item.
Once the UserFavorite table exists with it's two pointers, we can do a few things fairly easily. In your case, we have a few searching criteria:
each item must be at a given school
you want to limit your responses to the first 1000
To accomplish this you can combine two queries into one by calling matchesQuery.
Parse.Cloud.define("getAllFavoriteItems", function (request, response) {
var TestItems = Parse.Object.extend("TestItems");
var UserFavorites = Parse.Object.extend("UserFavorites");
var testItemsQuery = new Parse.Query(TestItems);
var userQuery = new Parse.Query(Parse.User);
var userFavoritesQuery = new Parse.Query(UserFavorites);
testItemsQuery.equalTo('school', 'Union College (NY)');
userQuery.include('Installation');
userFavoritesQuery.include('testItems'); //This makes sure to pull all of the favorite item data instead of just the pointer object
userFavoritesQuery.include('User'); //This makes sure to pull all of the favorite item data instead of just the pointer object
userFavoritesQuery.matchesQuery('testItem', testItemsQuery); //This will run this second query against the TestItems
userFavoritesQuery.matchesQuery('user', userQuery); //This will run the third query against Users, bringing the installation data along with it
userFavoritesQuery.limit(1000); //limit results to 1000
userFavoritesQuery.ascending('userId'); //group the user id's together in your array
userFavoritesQuery.find({
success:function(results) {
...
},
error:function(error) {
response.error();
}
})
})
Once we get that far, then compiling the push message for each user should be a matter of straight-forward string parsing logic. For example, in the success function, one way we can extract the data we is this:
success:function(results) {
var pushNotificationMessage = "";
var userId = "";
for (var i=0; i <results.length; i++) {
if (results[i].get('userId') != userId) {
if (results[i].get('userId') != "") {
//TODO send push notification
}
userId = results[i].get('userId');
pushNotificationMessage = ""; //start a new push notification
}
pushNotificationMessage += results[i].get('item').get('name') + ": " + results[i].get('item').get('location') + "\n";
}
response.success(true);
}
I haven't tested these examples to see if they'll work, but I hope this gives you an idea of how to simplify your queries into something a little more manageable.

Adding mutual friend count to each user in an array

I have an array of Facebook users (userList) and I want to store the number of mutual friends for each user in the array as a property (mfCount). I have checked that I am getting the correct number of mutual friends if I put in an individual user, but I'm not sure why I can't add this value to each user in the array?
function getfriends() {
FB.api('/me/friends', function(response) {
userList = userList.concat(response.data);
userCount = response.data.length;
for( i=0; i<response.data.length; i++) {
userId = response.data[i].id;
FB.api('/me/mutualfriends/'+userId+'/', function(response) {
userList[i].mfCount = response.data.length;
userCount--;
if(userCount === 0) { display_results();}
});
}
});
}
Have a look at the implementation below.
I've broken it out into multiple functions to separate each step.
When you're dealing with loops and callbacks, it becomes very important to keep track of what scope your anonymous functions are being defined in.
You can theoretically do it all in a one-liner like you were writing...
...but it gets very, very confusing as you go further and further into nested-callbacks.
One solution would be to make every variable inside each function 100% global, so that only i needs to have an enclosed reference. That's not really pretty, though.
Look through each function and take note of what parameters are going into the functions each step calls (or closures for callbacks). They're all needed (whether you separate them this way, or through closures in a one-liner or whatever).
The following worked just fine for me, inside of the Facebook developer sandbox (first time using the API).
The logs were for my benefit to see how the data was coming out, and to keep a basic stack-trace.
var userList = [],
userCount = 0;
function getfriends () {
//console.log("getFriends");
var url = "/me/friends";
FB.api(url, function (response) {
if (response.error && response.error.message) { return false; }
userList = userList.concat(response.data);
userCount = response.data.length;
compareAllFriends();
});
}
function compareAllFriends () {
//console.log("compareAllFriends");
var i = 0, l = userCount, userID;
for (; i < l; i += 1) {
userID = userList[i].id;
compareFriendsWith (i, userID);
}
}
function compareFriendsWith (i, id) {
//console.log("compareFriendsWith", i, id);
var path = "/me/mutualfriends/",
url = path + id + "/";
FB.api(url, (function (i) {
return function (response) {
//console.log(i, response);
var numFriends = (response.data) ? response.data.length : 0;
setMutualFriends(i, numFriends);
userCount -= 1;
//console.log(userCount);
if (userCount === 0) {
display_results();
//console.log("DISPLAYING");
}
};
}(i)));
}
function setMutualFriends (i, friendcount) { userList[i].mfCount = friendcount; }

Categories